|
-
May 29th, 2003, 10:48 PM
#1
How to Call base Class Constructor
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.
-
May 29th, 2003, 11:20 PM
#2
One solution is the :: operator.
X::X()
Kuphryn
-
May 29th, 2003, 11:37 PM
#3
I would do it in the initialization list of the constructors.
Code:
class X
{
public:
X();
X(int);
} ;
class Y : public X
{
public:
Y():X() {};
Y(int i):X(i){};
};
quoted from C++ Coding Standards:
KISS (Keep It Simple Software):
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
Avoid magic number:
Programming isn't magic, so don't incant it.
-
May 29th, 2003, 11:41 PM
#4
Re: How to Call base Class Constructor
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.
Code:
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
Last edited by Paul McKenzie; May 29th, 2003 at 11:48 PM.
-
May 29th, 2003, 11:47 PM
#5
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
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|