-
Constructor inheritance
Hello everyone, I have the following question: consider this code:
Code:
#include <iostream>
class father
{
protected:
int a;
public:
father() : a(1000) {}
father(int b) : a(b) {}
int geta() { return a; }
void seta(int b) { a = b; }
};
class son : public father
{
public:
void reset() { a = 1000; }
};
int main()
{
son test1;
//son test2(2);
std::cout << test1.geta() << std::endl;
return 0;
}
Now, since the output this code yields is "1000", it's clear that the standard constructor of class father is being inherited to class son. But, if I remove the comment marks in main, I get a compiler error, which means the second constructor, the one that takes an integer, is not being inherited. Do I have to write it explicitly in the definition of class son? But then I'd have to rewrite the standard constructor for son, since a non-standard constructor would be present. I thought the whole point of inheritance was avoiding things like this?
Another question: if I rewrite the constructors for class son, the compiler won't let me do it in this way: "son(int b) : a(b) {}", like I do it for father, but won't complain if I do it like this: "son (int b) {a = b;}" Anyone knows what's going on? By the way, I'm using Visual C++ 6.
Thanks!
-
no constructors are inherited. derived calls default base con in son Test1() as no param is passed.
son test(2) s an error. son doesnt have a constructor that takes an int.
If the base class default con is not the one you want called then provide an adequate con in the derived that calls the appropriate base class constructor explicitly.
-
So, when you derive a class from another, all non-standard constructors that the original class has are lost? Then what's the point of inheriting? I know, you can still use the member functions, but they won't do much if you can't create your derived object the way you want...
Oh well, I guess that's the way it is, and one has to write his own constructors... sigh.
-
I think you can do this:
Code:
class A
{
public:
A(int n):num(n){}
private:
int num;
};
class B : public A
{
public:
B(int n):A(n){}
};
Is that what you want?
Edit: Guess stoned_coder already said that... :D