mo*******@hotmail.com (pantalaimon) writes:
I'm trying to write a GUI for a game I'm making. Till now I've always
done this: ChildClass(int x,int y) : ParentClass(x,y) whenever my
compiler complains about "no default constructor found". But in one of
my classes I need to do some calculations first and THEN call the
parent's constructor. Here is an example:
class ParentClass
{
public:
Parentclass(int sum);
};
class ChildClass : public ParentClass
{
public:
ChildClass(int x,int y)
{
int sum = x + y;
ParentClass(sum);
}
This doesn't work because the constructor of ParentClass is called
automatically before processing the constructor of ChildClass You can not work
around this, because the code is inserted by the compiler, but you can
do the following:
ChildClass(int x, int y) : ParentClass(x+y)
{
}
By doing this the compiler shouldbe satisfied and should do the right
thing.
BTW You can make the scenario I described "visible" by trying this:
#include <iostream>
using namespace std;
class Base
{
public:
Base()
{
cout << "Base::Base() called" << endl;
}
~Base()
{
cout << "Base::~Base() called()" << endl;
}
};
class Derived : public Base
{
public:
Derived()
{
cout << "Derived::Derived() called" << endl;
}
~Derived()
{
cout << "Derived::~Derived() called" << endl;
}
};
int main()
{
Derived object;
return(0);
}
The output should be:
Base::Base() called
Derived::Derived() called
Derived::~Dervied() called
Base::~Base() called
HTH && Kind regards,
Nicolas
--
| Nicolas Pavlidis | Elvis Presly: |\ |__ |
| Student of SE & KM | "Into the goto" | \|__| |
|
pa****@sbox.tugraz.at | ICQ #320057056 | |
|-------------------University of Technology, Graz----------------|