Hello, I've got a question involving simple class inheritance.
I'm trying to compile a code like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
class A
{
public:
A() { /* construct the A object*/ }
};
class B : public A
{
};
class C : public B
{
public:
C() : A() { /* construct the C object*/ }
};
I basically invoke the construction of class A before constructing the C object. But the compiler complains that A is not a direct base class of C so I cannot use the A() constructor this way.
I tried this syntax: C() : B::A() { /* construct the C object*/ }
But the result was the same.
My question is is there a way I can call the constructor of a base class if this class is not a direct base class of the caller. It's obvious which constructor should be called, why does the compiler complain?
Well, of course, I can always use an initialization method, but that's beside the point.
A constructor of a child will always call the constructor of it's parent. You need to put it in an initializer list only if the constructor you want to call is not the default one. So, C() calls B() which calls A(). If you tell C() to call A(), A() gets called twice and that could be a big problem, thus it is illegal.
It was a bad example. I'm talking about non-default constructors. I realised that C() calls the default constructor of A but if there's no default constructor or if I need to call a constructor with arguments...
class A
{
// some variables
public:
A( int arg1, double arg2 /*, etc.*/ )
{
/* some complex algorithm to assign values to the variables
using the arguments as parameters */
}
};
class B : public A
{
};
class C : public B
{
public:
C( int arg1, double arg2 /*, etc.*/ )
{
/* I don't want to write the whole algorithm again
I just want to call A() with the appropriate arguments */
}
};
Can you show me how to use this initialization list you're talking about, hamsterman.
EDIT: In my case B is an abstract class with pure virtual functions and stuff. So there's no way I can declare a constructor in B to link C to A constructor. Otherwise it's obvious: you call C( args... ) which calls B( args... ) which calls A( args... )
I guess that makes sense. As long as I don't try to initialize members of the abstract class everything is OK.
I thought you were talking about this kind of initialization: C( args... ) : var1( arg1 ), var2( arg2 ) { ... }
Nevermind, that fixed my problem! Thanks man, I'll drink a beer to you, today!