mrwad99
asked on
Derived class with default function parameters: needs explanation please !
Ah; hello !
This is a hardcore C++ question that I am hoping can be resolved by someone who can give me a solid explanation.
Please peruse this code:
class A
{
public:
A() {}
virtual int GetVal(int a = 1) { return a; }
};
class B : public A
{
public:
B() {}
virtual int GetVal(int b = 2) { return b; }
}
main()
{
A *x = new B();
int r = x->GetVal();
}
Confusion: r is 1. Now I know this, but would like solid explanation and clarification as to *why*.
Firstly we are dealing with pointers, so that allows run time binding, right ? And we are creating a B object but assigning it to an A pointer. So why is the output not 2 ? Arghhhh !
TIA
This is a hardcore C++ question that I am hoping can be resolved by someone who can give me a solid explanation.
Please peruse this code:
class A
{
public:
A() {}
virtual int GetVal(int a = 1) { return a; }
};
class B : public A
{
public:
B() {}
virtual int GetVal(int b = 2) { return b; }
}
main()
{
A *x = new B();
int r = x->GetVal();
}
Confusion: r is 1. Now I know this, but would like solid explanation and clarification as to *why*.
Firstly we are dealing with pointers, so that allows run time binding, right ? And we are creating a B object but assigning it to an A pointer. So why is the output not 2 ? Arghhhh !
TIA
ASKER
So you are saying that as a general rule, default parameters are resolved at compile time always ?
I have just tried the same without pointers and the default value is taken from the type being assigned *to*, in this case I.
I am still a little confused however as to why it is taking the default from I when it can clearly see that I want to make an B object...
I have just tried the same without pointers and the default value is taken from the type being assigned *to*, in this case I.
I am still a little confused however as to why it is taking the default from I when it can clearly see that I want to make an B object...
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
OK. I guess I need to re-read about virtual functions and late binding then.
Thanks.
Thanks.
No, in general, you would be right. I't's just that 'default parameter' thingy that messes things up here.
class I
{
public:
virtual int GetVal(int a = 0) = 0;
};
class A : public I
{
public:
A() {}
virtual int GetVal(int a = 1) { return a; }
};
class B : public A
{
public:
B() {}
virtual int GetVal(int b = 2) { return b; }
}
main()
{
I *x = new B();
int r = x->GetVal();
}
'r' will be (in fact is) 0...