Dave
Dave

Reputation: 119

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;
}

Upvotes: 2

Views: 2574

Answers (4)

Mohit Jain
Mohit Jain

Reputation: 30489

You need to do the following:

A *aa = *c;

which would be equivalent to:

A *aa = c->operator A*();

On the other hand A* a = b; is an example of upcasting which happens implicitly in C++ and many other languages.

Note that you have defined operator for class B and class C and not for pointers to these classes.

Check live demo here

Learnings: There is no implicit conversion to pointers of unrelated types.

Upvotes: 1

Daniel
Daniel

Reputation: 1447

A pointer can only ever point to objects of its own class, or to objects of a derived type. Since C does not inherit from A, your code will not work.

I would strongly recommend you have a look at "C++ in 21 days" (search online), the pointer and references section.

Upvotes: 0

Deduplicator
Deduplicator

Reputation: 45654

The conversion operator is not called, because there is no fitting one.

Actually, there cannot be a fitting one, as you are trying to assign from a pointer to one type to a pointer to a different, non-base type.

You can only override operators if you have at least one user-defined type, but the argument is a pointer, and thus not a user-defined-type, and the result (the conversion-operator is the only one where the result is matched) is not either.

Upvotes: 1

jrok
jrok

Reputation: 55395

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).

Upvotes: 2

Related Questions