Click to See Complete Forum and Search --> : How to Call base Class Constructor


Exceter
May 29th, 2003, 10:48 PM
hi
help me with the following plz, I have base class , it has two constructors, in derived class I want to call the base classes different constructors
for ex.,
class X {
public:
X();
X(int);
} ;
class Y : public X {
public:
Y();
f() {//call X()};
G() {//call X(int)};
};

how can I call in 1-function one constructor, and in second function second constructor of the base class?

tnx.

kuphryn
May 29th, 2003, 11:20 PM
One solution is the :: operator.

X::X()

Kuphryn

Kheun
May 29th, 2003, 11:37 PM
I would do it in the initialization list of the constructors.


class X
{
public:
X();
X(int);
} ;

class Y : public X
{
public:
Y():X() {};
Y(int i):X(i){};
};

Paul McKenzie
May 29th, 2003, 11:41 PM
Originally posted by Exceter
class X {
public:
X();
X(int);
} ;
class Y : public X {
public:
Y();
f() {//call X()};
G() {//call X(int)};
};
There is a reason why those functions are called constructors. What you are asking is impossible. How can you call the constructor if the derived class has already been constructed? Constructors are only called when constructing objects.

If you want to call a function in class X, make it a regular (non-constructor) function and call it from your Y class.

class X {
public:
X() { DoXFunc(); }
X(int n) { DoX2Func(n); }

protected:
void DoXFunc() { }
void DoX2Func(int n) { }
};

class Y : public X {
public:
Y();
void f() { DoXFunc(); }
void G() { DoX2Func(1); }
};

And if from the Y constructor, you wanted to call a certain X constructor, you use something called a member-initialization list. But the bottom line is that you don't call constructors explictly, constructors are called automatically whenever you create an object.

Regards,

Paul McKenzie

Paul McKenzie
May 29th, 2003, 11:47 PM
Originally posted by kuphryn
One solution is the :: operator.

X::X()

Kuphryn What compiler allows this? This is illegal syntax -- you can't call a constructor directly.

Regards,

Paul McKenzie