Simple class inheritance question

Asked 2 years ago, Updated 2 years ago, 91 views

It's a simple question.

class CObj
{
    virtual int Add();
};

class CUnit :public CObjs
{
    virtual int Add();
    virtual void Check();
};

If there is a simple inheritance structure as follows: Can I normally access check in the child class with CObj pointer?

If access is not possible normally, the check function must be implemented on the parent side Is it possible to access the check function on the child side with the parent pointer?

c++ class inheritance

2022-09-21 21:07

3 Answers

I think you left out public: but let's assume you have one.

CObj* p = new CUnit();

As above, the address p points to is actually an instance of CUnit, but p is a pointer to CObj, so only members declared in CObj can access it.

Therefore, it is not accessible under the circumstances you mentioned.

If you want to invoke check() in CUnit, you must either use the method of declaring the corresponding member function in CObj or downcast p.

You can use static_cast or dynamic_cast for downcasting. Static_cast should be used when it is clear that the address is of the destination type. For example, if the object of the address pointed to by p can be CUnit or CUnint2, incorrect casting will occur.

Because dynamic_cast calculates the inheritance relationship at runtime, the programmer can handle it by telling you if casting is not possible as shown below.

CObj* p = new CUnit();
if (CUnit* p2 = dynamic_cast<CUnit>(p))
    p2->check();


2022-09-21 21:07

I don't think it's accessible

A lookup table is created only when the parent declares virtual, mapping functions with the same name on the inherited side

Without such a declaration, the parent class' pointer will be error-free because it doesn't know what the child has.

In this case, you need to downcast the parent pointer to access it.


2022-09-21 21:07

Normal access is not possible.

Compulsory access is possible. As you said, it's accessible through downcasting, but I think it's going to be unpredictable~


2022-09-21 21:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.