简体   繁体   中英

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

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM