-1

I have a trivial inheritance case following:

class Person {
public:
    const char* name;
public:
    Person()
        : name("Unknown person") {}
    
    Person(const char* name)
        : name(name) {}
};

class Student : public Person {
public:
    Student()
        : Person("Unknown Student") {}
};

If I assign a child pointer to a parent pointer, it is totally legal:

Student *s = new Student();
Person *p = s;

But if I do the other way, assigning a parent pointer to a child pointer, it would cause an error:

Person *p = new Person();
Student *s = p;

The error is: invalid conversion from ‘Person*’ to ‘Student*’.

An example where this might be useful is: I have a Person class, and depends on where this person will do in life, I will transform it into Student, Teacher, etc.

Any suggestions?

rturrado
  • 7,699
  • 6
  • 42
  • 62

1 Answers1

3
Person *p = s;

works because every Student is also a Person.

Student *s = p;

doesn't work because a Person is not necessarily a Student.

Lukas-T
  • 11,133
  • 3
  • 20
  • 30
  • Can't use dynamic_cast with the code as posted, since the base class does not contain any virtual functions. – john Jan 16 '21 at 08:08
  • @john Thanks for the reply, really help me a lot. So why only with virtual functions, I can use dynamic_cast? –  Jan 16 '21 at 08:53
  • @AnhTran If a class has one or more virtual fucntion then something called a *vtable* will be added by the compiler to the class. This makes the class a little bit bigger than it would be otherwise (typically it makes the class bigger by the size of a pointer). A vtable is also needed to implement dynamic_cast, so the C++ rules say that you must already have at least one virtual function for dynamic_cast to work. – john Jan 16 '21 at 09:05