Samir
Samir

Reputation: 235

How to access a private variable in a class without using allocation?

I'm trying to better understand the memory allocation / pointers etc..

As you can see on "test" Method , I tried to access the Name of CTest class so that I can fill it in my Schedule array . Is there a possiblity to access the CTest class without allocation ( CTest * Test = new CTest(); ) . I mean is it possible to use here only pointers to access the variable Name of CTest ?

This is my program :

class CTest
{
    public:
    void setName(std::string str){ Name = str;}
    std::string getName(){return Name;}

    private:
    std::string Name;
};

class CEvent
{
public:
    CEvent() = default;
    void setTestName(std::string str){Test->setName(str);}
    std::string getTestName(){return Test->getName();}
     ~CEvent(){};
private:
    std::string Name;
    CTest *Test = new CTest();   //Here
};

class CBlock
{
public:
    CBlock() = default;
    friend class CBooking;
    ~CBlock(){}

private:
    CEvent *Schedule[7][5];
};

class CBooking
{
public:
    CBooking() = default;
    void test();
    ~CBooking(){}

private:
    CBlock *Sched;
};

void CBooking::test()
{ 
   Sched = new CBlock();
   Sched->Schedule[3][2] = new CEvent();

   std::string a = "test2";
   Sched->Schedule[3][2]->setTestName(a);

   std::cout << Sched->Schedule[3][2]->getTestName();
}

int main()
{
    CBooking a;
    a.test();
    return 0;
}

Upvotes: 0

Views: 91

Answers (1)

Kevin
Kevin

Reputation: 7324

If you want to give CEvent an existing CTest object then pass it as a reference in the constructor:

class CEvent
{
public:
    CEvent(CTest &test): test(test) {}

    void setTestName(std::string str){test.setName(str);}
    std::string getTestName(){return test.getName();}
private:
    CTest &test;
};

...

CTest test;
CEvent event(test);
event.setTestName("test");
std::cout << event.getTestName() << "\n";

If you want to be able to copy/move CEvent objects around (or change the CTest object one is holding) you'll need to make the test member a pointer rather than a reference, e.g. CTest *test; and initialize it in the constructor like this: CEvent(CTest &test): test(&test) {}. It's still a good idea to pass it to the constructor as a reference to ensure that it won't be null.

Upvotes: 1

Related Questions