Serious Sammy
Serious Sammy

Reputation: 99

Accessing Objects C++

Well I think this might be a very easy Question but I still don't know what I'm doing wrong. This is my problem:

I have 3 classes, lets call them A,B and C

a.h

class A
{
    public:
    B *b_object;
    C *c_object;
}

a.cpp

A()
{
   b_object = new B;
   c_object = new C;
}

so we actually have two objects, one of b and c when we create an object of a.

b.h

#include "a.h"

class B is also including the a.h but i can't access the c_object form the b_object like

c_object->do_stuff();

Why is this not working? I thought with *c_object is created on heap and through the #include "a.h" in b.h I should be able to access it.

Well thanks in advance, Sammy

Upvotes: 1

Views: 120

Answers (2)

AFM
AFM

Reputation: 44

If I'm not mistaken, you have circular dependency in the problem: 1) B.h is included in A.h. 2) A.h is included in B.h.

because A needs to know members of B to initialize its B pointer and B needs to know the members of A to do whatever it is you are trying to accomplish. Thus creating circular dependency.

http://en.wikipedia.org/wiki/Circular_dependency

Also, just because you included A.h in B.h doesn't mean you have access to A's data members. You would have to have an existing object A (inside of B) for you to access the pointer C.

Or you can make it so that B is a derived class of A, so B will inherit the private data members of A, which will then allow you to access pointer C.

Upvotes: 0

Tushar
Tushar

Reputation: 8049

You should understand encapsulation, which is a major feature of C++ and Object-Oriented Languages in general.

Since your c_object is defined inside the A class, it can only be accessed by an A object (unless you specify otherwise).

Your b_object is also in the A class, but that doesn't mean it can access the c_object. For example, let the b_object be the door of a car and the c_object be the tires. The car itself is the a_object. Just because a car has both a door and some tires doesn't mean the door should be able to make the tires do something. Only the car is able to access both.

Upvotes: 1

Related Questions