PDA

View Full Version : C++ method call



^NyAw^
18th November 2011, 12:58
Hi,

I have class structures like this:


class classA
{
...
classA() //Constructor
{
foo();
}
virtual void foo()
{
//Do nothing
}
...
};

class classB : public classA
{
...
classB() : classA() //Constructor calls classA constructor
{
...
}
void foo()
{
//Specific code here
}
...
};


When I create an object of classB, it calls the constructor from classA.
The constructor of classA calls the method "foo()" that is redefined in the classB.
The problem is that "foo()" is executed from classA instead of classB.

Does anyone know how I must do this?

Thanks,

Lykurg
18th November 2011, 13:41
Since the constructor of classA is called before classB, the only chance you have is to create a init() method and call it from the classB constructor.
#include <QtGui>

class classA
{
public:
classA()
{
init(); // or don't call it if classA is abstract
}

virtual void init()
{
qWarning() << Q_FUNC_INFO;
foo();
}

virtual void foo()
{
qWarning() << Q_FUNC_INFO;
}
};

class classB : public classA
{
public:
classB() : classA()
{
init();
}
virtual void foo()
{
qWarning() << Q_FUNC_INFO;
}
};


int main(int argc, char *argv[])
{
QApplication app(argc, argv);
classB b;
return 0;
}

^NyAw^
18th November 2011, 15:09
Hi,

Thanks Lykurg.

This is the way that i did before but I was trying to not have to call "init()" from every derived class.

Thank you anyway

AlexMalyushytsky
19th November 2011, 02:30
You can not call virtual functions from constructor.
Such behavior is undefined - your class instance is not constructed yet.

Regards,
Alex

Zlatomir
19th November 2011, 12:19
@Alex, it is not undefined behavior, only the "overriding" doesn't work.

Overriding works only after the whole object is created because the objects are created from base class "down" - the base c-tor can't call a method in derived class since that slice of the object isn't created yet (or more correctly it's not yet initialized), so from c-tors and d-tor it's always the member function from the same class that gets called - so don't expect overriding.