Need suggestion on referance vs pointer

New to c++ and i have confusion about whether aObj should be a referance or pointer here. Basically in the main program an object of class B will be created and class A's functions need to be accessed via this ptr/referance of class B.
And how should i write constructor for class B which will take classC's object as input and assign it to that pointer/referance, i mean can i use initialiser list to do that. Please throw some light on this

class A
{
public:
virtual void testA() = 0;
};

class B
{
public:
int m_id;
//Need to have pointer/referance of class A as member here which should point to class C's object.
B(int id): m_id(id)
{
}

virtual void testB() = 0;
};

class C:public A
{
public:
void testA();
}

class D:public B
{
public:
void testB();
}
It sounds like you want something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class A
{
public:
virtual void testA() = 0;
};

class C:public A
{
public:
void testA();
}

class B
{
public:
int m_id;
A *a;  // or A &a
B(A *a_p) : a(a_p) {}
B(int id): m_id(id)
{
}

virtual void testB() = 0;
};

class D:public B
{
public:
void testB();
}


Have I got that right?

Some things to ask yourself to decide whether it will be a pointer or a reference:
- can B.a change? I mean can you change it to point to another A object? If so then you must use a pointer. Once created, a reference always refers to the same object.

- Can B.a be nullptr? If so, then it should be a pointer. A reference should always refer to an actual object.

Regardless of whether it's a pointer or a reference, be sure that whatever it pointers/refers to outlives the B object. In other words, you don't want the A object to be destroyed while you still have a B object pointing to it.

Hope this helps.
thank you so much for the clear explanation
Topic archived. No new replies allowed.