Search code examples
c++castingtype-conversionconversion-operator

C++ cast operator of pointer


I tried the following code sample but A* aa = c; does not compile. Why is the conversion operator not called? The same example without pointers works. So I do not know why C must inherit from A? Thanks for your help.

EDIT: I know coding something like this makes no sense. But I just want to understand the conversion stuff.

#include <iostream>

using namespace std;

class A {    
public:
  int mValue = 0;
};

class B : public A{
public:
  operator A*() { 
    return this;
  }
};

class C {
public:
  operator A*() {
    return new A();
  }
};

int main(int argc, char* argv[])
{
  B* b = new B();
  A* a = b;

  C* c = new C();
  A* aa = c;
}

Solution

  • Because expression c has type C*, not C, which is required for the conversion operator to be called. C* and A* are unrelated types and no conversion exists between them.

    A* aa = *c;
    

    would work.

    A* a = b; works because conversion from a pointer to derived class to a pointer to base class is legal and implicit (it doesn't call the conversion operator, mind you).