954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Accessing a method from class 1 in class 3

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

flash121
Light Poster
49 posts since Jan 2008
Reputation Points: 10
Solved Threads: 0
 

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;
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You