0

Ok so i'm trying a few things with inheritance, heres the code:

class A {
protected:
    int i;
public:
    A() :i(0) {}
    A(int n):i(n) {}
};

class B :public A {
public:
    B() :A() { }
    B(int n):A(n) { }

};

I know that you can affect a pointer to parent with a pointer to child, and i understand why:

B* b = new B();
A *a(0);
a = b;

But i also found out that you can do this:

A ac = *b;

or

A &ac = *b;

But isnt it literally affecting the object b to ac, instead of just pointer to memory location?

By the way, i'm not completely sure of what using & does in a declaration, I understand it as a default pass by reference.

1 Answers1

4

First of all you need to understand that C++ does not always protect you to do wrong things. Just because you can write some code that does not trigger a compiler error does not mean that it is correct and meaningful code.

In general A ac = *b; is wrong when A is a base class of b. *b is a B and assigning that to an A will slice all members of B. In your example B has no additional members, but in general object slicing is bad and one needs to take care of that.

On the other hand, this

A& ac = *b;

is fine always, because ac is just a reference to an A. It is similar to

A* ap = b;

as you can only use As interface on ac. No copy is made here and the actual object (referenced by ac) is still a B.


By the way, i'm not completely sure of what using & does in a declaration, I understand it as a default pass by reference.

The symbol & has different meanings depending on context. In A& ac = *b; it is part of the type: reference to A. This is the same as when passing an argument by reference to a function. You only need to consider a quirk in the grammar, that makes A& ac=*b, ac2; declare one A& called ac and one A called ac2. It is best to declare only one variable per line.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185