user14749247
user14749247

Reputation:

C++ Inheritance: Variable with Type of a Base Class

Let's imagine we have two classes.

class Base {};

class Derived : public Base {};

In another part of my code I want to have a variable of type Base which can also hold an object of type Derived.

Base b1, b2;
b1 = Base();
b2 = Derived();

In languages like Java or C# this is possible. In c ++, however, I get a slicing error.

Is there a way to replicate the behavior of for example Java in C++?

Upvotes: 1

Views: 1348

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 595369

In languages like Java and C#, object variables are reference types. The actual objects are stored somewhere in dynamic memory, and the variables just refer to them, like pointers.

But in C++, objects can be created in automatic memory, static memory, dynamic memory, etc. So when you have an object variable, that is the actual object, not a reference to the object.

There is no way to make C++ work the way you want for value types, only for reference types. So you MUST use a pointer/reference instead, otherwise slicing will occur, as you have already discovered. Polymorphism requires the use of pointers/references in order to handle virtual dispatch correctly, etc.

Base b;
Derived d;
Base &b1 = b;
Base &b2 = d;
Base *b1 = new Base;
Base *b2 = new Derived;
...
delete b1;
delete b2;

Upvotes: 2

Mohammed Ibrahim
Mohammed Ibrahim

Reputation: 101

You can use pointers to accomplish that, ie this will work:

Base* bs=new Derived();

If you want to call a function that is defined in Derived, do the following:

((Derived*)bs)->fn();

Upvotes: -1

Related Questions