Link to home
Start Free TrialLog in
Avatar of mrwad99
mrwad99Flag for United Kingdom of Great Britain and Northern Ireland

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
Avatar of jkr
jkr
Flag of Germany image

The default parameter's value is deducted from the pointer type (where else should the compiler get that info from?) - consider the following:

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...
Avatar of mrwad99

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...

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mrwad99

ASKER

OK.  I guess I need to re-read about virtual functions and late binding then.

Thanks.
No, in general, you would be right. I't's just that 'default parameter' thingy that messes things up here.