0

It seems that implicit cast from cont to non-const parent class is ok with gcc, can someone explain me why?

class A
{
public:
    A() = default;
    int& get()
    {
        return a;
    }

private:
    int a = 2;
};

class B : public A
{
public:
    B() = default;
};
const B b;
A a = b;  //< Why this line of code compiles?!

a.get() = 23;
blaizard
  • 216
  • 2
  • 8

2 Answers2

3

Because you're not casting it, you're copying the content of it.

const int x = 5;
int y = x; // completely valid, because it just copies.

Doing this would fail: https://godbolt.org/z/UeT_VW

JohnkaS
  • 622
  • 8
  • 18
2

This isn't really an implicit cast. It's using the copy constructor of A. Your variable a isn't another name for the A subobject in b; it's a different object of type A which was created by copying the A subobject in b. This is a form of "object slicing".

To have another name for the same object instead of creating another object, you use a reference. Note using this line instead does fail to compile, because it removes the const:

A& a = b;
aschepler
  • 70,891
  • 9
  • 107
  • 161
  • Re: "This isn't really an implicit cast." Indeed. There is no such thing as an implicit cast. The question is about an implicit **conversion**. – Pete Becker Sep 29 '19 at 21:21
  • Oh of course thanks! I don't how I missed this I guess it's too late :) – blaizard Sep 29 '19 at 21:22