Reputation:
quick question: I have a base class with a member variable and I'm trying to 'override' this value in a derived class. How do I do this exactly?
I tried:
class A
{
public:
double i = 1;
};
class B : public A
{
public:
double i = 2;
};
int main(int argc, char** argv)
{
B* b = new B();
A* a = b;
std::cout << b->i << '\t' << a->i << std::endl; // output 2 1
}
But the desired output is '2 2'. What am I doing wrong?
Thanks,
Niklas
Upvotes: 0
Views: 663
Reputation: 363
There is even a simplier solution than Pete proposed.
Just define your class B like this:
class B : public A
{
public:
B() { i = 2; }
}
So that class B will reuse the member i defined in its base (A) and its default value will be "overriden" to 2 so your test code will return "2 2".
That's how you 1) don't change the base class A (don't add that unnecessary int argument with a default value, some people even say that function parameters with default values is a bad practice in c++) and 2) don't add an overhead of virtual functions to your classes (which is also unnecessary in your simple code).
Upvotes: 0
Reputation: 76305
You can override virtual functions; you can't override data members. This class hierarchy has two different members named i
, one in class A
and one in class B
.
If you want the derived class to change the value of i
that's in the base class, just do it in the constructor: B() { i = 2; }
. But a better approach would be to have a constructor for A
that sets the value of i
, and to call that from B
:
A::A(int ii = 1) : i(ii) {}
B::B() : A(2) {}
Upvotes: 1