WideWood
WideWood

Reputation: 569

Access to member function in class using pointer to other class

I have a simple class with private field and constructor with public member function to print all object names from other classes.

Here is code from header file:

class Class8 : public Class6, public Class7
{
    private:
        std::string object_name;
    public: 
        Class8(std::string object_name_);
        void print_all();
};

Class6 code in header file:

class Class6 : public Class2, public Class3
{
    private:
        std::string object_name;
    public: 
        Class6(std::string object_name_);
        void print_name(); //prints name of this classs object (values of "object_name" private field)
};

As you can see Class8 extends public classes 6 and 7.

For example I create pointer to Class6 and then Class8 object. Then I assign address of Class8 object to pointer to Class6 using & operator and after I try to call print_all() (method of Class8) using pointer that contains address of Class8 object like this:

    Class6* pointer_to_six = new Class6("Class_x"); 
    Class8 object_8("Object_name");
    pointer_to_six = &object_8;
    pointer_to_six->print_all();

But compiler says that class Class6’ has no member named ‘print_all’. What have I done wrong?

Upvotes: 0

Views: 66

Answers (2)

Jiri Volejnik
Jiri Volejnik

Reputation: 1089

The Class6 really does not have any method named "print_all". It's the Class8 that has it. Therefore, you need a pointer of type Class8* to call the print_all.

Perhaps what you're looking for is dynamic_cast:

if (Class8* pointer_to_eight = dynamic_cast<Class8*>(pointer_to_six))
    pointer_to_eight->print_all();

However, for this to work, you need Class6 to have at least one virtual method.

Moreover, you have to remove the "object_name" member from Class8, because it would clash with the member of the same name in Class6.

Upvotes: 0

Lucas Streanga
Lucas Streanga

Reputation: 477

The reason this occurs is because pointer types matter. Your pointer_to_six points to a class8 object which does contain print_all, but it is of type class6 *. So, it is dereferenced as a class6 object, and class6 does not contain a member named print_all.

There are a few solutions. You may use casts to convert the pointer types. You may use c-style unsafe casts to say ((Class8 *) pointer_to_six)->print_all(); or you may use more safe C++ casts like static_cast.

You may also make use of virtual functions. That is, each class implements the same function differently.

Upvotes: 2

Related Questions