Hello,

Lets say i have 3 classes called class1, class2 and class3. Class1 has a method which returns a value, in class2 there's a pointer variable to class1(lets say class1* c1) and in class3 there's a class2 type variable(class2 c2). I would like to access the method from class1 through class3. I've tried c2.c1->method(), which doesnt work because the variables are private. Is there any other way to doing this besides simply making c1 public ?

Thanks in advance

use friend functions

#include <iostream>
using namespace std; 

class c2;
class c1
{
public:
    friend c2;
    c1() {}
private:
    void SayHello() {cout << "Hello\n";}
};

class c2
{
public:
    c2() { p1 = new c1;}
    ~c2() {delete p1;}
    void Hello() {p1->SayHello();}
private:
    c1* p1;
};

class c3
{
public:
    c3()
    {
        c2 o2;
        o2.Hello();
    }
};

int main()
{
    c3 o3;

    return 0;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.