Kevin Del Castillo Ramirez Kevin Del Castillo Ramirez - 9 months ago 62
C++ Question

Derived Class Constructor from an Abstract Class

I have a problem with Derived Class from an Abstract Class

#include <iostream>

using namespace std;

class A
int a,b;
A(): a(0), b(0) {}
A(int na,int nb): a(na), b(nb) {}
virtual void print() = 0; // Reason to be an abstract class

class B : public A
B(int a, int b) {A(a,b);}
void print()
cout << a << endl;
cout << b << endl;

int main(){

B clase(3,2);
return 0;

The above code give me an error like this:

lab1.cpp: In constructor ‘B::B(int, int)’:
lab1.cpp:20:10: error: invalid cast to abstract class type ‘A’
lab1.cpp:5:7: note: because the following virtual functions are pure within ‘A’:
class A
lab1.cpp:12:16: note: virtual void A::print()
virtual void print() = 0;

Note: I know how to make it works, the B constructor will look like this:

B(int a, int b): A(a,b) {}

But my real question is, what if I want to call the constructor of my derived class within the branches (like the above code)?
What is the correct way to call the abstract constructor within the branches?

Answer Source

What is the correct way to call the abstract constructor within the branches?

There is none.

There is a very good reason for this. The superclass has to be constructed before your class can be constructed.

When you write the code for the constructor you have a reasonably constructed object. Your parent is constructed at the very least.

This is neatly expressed with the initialing syntax for the constructor.

B::B(int a, int b):A(a, b) {  
     // A is complete. now we can do stuff.