1

I have the following code to print the derived structure variable in a global function. But when I tried to compile the code, g++ returns the following error. Is it not possible to typecast the structure to a derived class from base class which is passed to the function by pass by value?

In function 'void print(B)':
Line 19: error: no matching function for call to 'D1::D1(B&)'

Code:

struct B{
    int a;
    B()
    {
        a = 0;
    }
};

struct D1:public B{
    std::string s1;
    D1()
    {
        s1.assign("test");
    }
};

void print(B ib)
{
    cout << static_cast<D1>(ib).s1<<endl;
}

int main()
{
    D1 d1;
    cout << d1.s1 <<endl;
    print(d1);
    return 0;
}
Griwes
  • 8,805
  • 2
  • 43
  • 70
Ravi
  • 653
  • 3
  • 10
  • 21
  • Uh-oh, what a rubbish code... ever heard of *constructor initializer list*? – Griwes Sep 14 '12 at 11:11
  • @Griwes: I know about constructor initializer list. I copied the code which I tried in my machine. Sorry about that. – Ravi Sep 18 '12 at 20:03

1 Answers1

4
void print(B ib)

D1 d1;
print(d1);

Your object is truncated to B in print function. You should use reference or pointer instead of value.

cout << static_cast<D1>(ib).s1<<endl;

Use static_cast<D1&>(ib).s1. In both cases ib should be reference!

ForEveR
  • 55,233
  • 2
  • 119
  • 133
  • 1
    Indeed. http://stackoverflow.com/questions/274626/what-is-the-slicing-problem-in-c – BoBTFish Sep 14 '12 at 11:14
  • 1
    `dynamic_cast` only works for polymorphic types. It's much better to change the argument type to `D1` (perhaps with a `const` and/or a `&`) if that's what the function requires. – Mike Seymour Sep 14 '12 at 13:23
  • @BoBTFish:Link explained me the slicing problem. Thanks alot – Ravi Sep 18 '12 at 20:12