I have to work with a tree based hierarchy of objects where I need to access the deepest element that contains the data required by the application. I'm not sure if the previous statement explains in its best the problem itself so its better to present it with an example. Given the following scenario:
class A {
private:
B* _b;
public:
B* getB() {return _b;}
};
class B {
private:
C* _c;
public:
C* getC() {return _c;}
};
class C {
private:
int _n;
public:
int getN() {return _n;}
};
The desired operation would be to access n via A. So I would call the following:
A foo;
foo.getB()->getC()->getN();
The problem comes when any of the parts of the path are null we end up having a core dump. In the above scenario if B is null we end up in a core dump scenario.
Therefore I seek help and advice on any strategy or pattern that I can use to avoid this core dumps scenarios. If the path is extremely big I end up checking every single pointer if its valid and end up having really ugly code and also risk that I might have missed checking a part of the path. Note: I do not have access to change the implementation of the hierarchy of classes (A,B,C) as they are generated code and I do not have access to change the generator. Changing the previous would be my preferred solution but unfortunately I cannot.
In order to avoid having null pointers, you may want to establish a class-invariant that the member is never null. This can be achieved with following steps:
Encapsulate access to the member so that nothing outside the class can set the member. You've already achieved this through the use of private access. Just make sure that you pass/return a reference or a pointer to the member from a member function to the outside.
Ensure that no member nor friend function ever sets the member to null.
Also ensure that the member is always initialised. This is achieved by use of a custom constructor. Example:
class A {
B* b;
public:
A(B* b) : b(b) {
if (!b) {
// unlike indirection through null pointer, an exception can
// be caught and (potentially) handled gracefully at runtime
throw std::runtime_error("Naughty!");
}
}
// following prevents passing null literal at compile time
A(std::nullptr_t) = delete; // nullptr
A(int) = delete; // 0
// since it is never null, we can safely return a reference
B& getB() {return *b;}
}
While references have the nice property of not being ever null, they are tricky as members, since they are also not assignable. As an argument to a constructor, they are tricky since it is generally not conventional or expected for a class object to keep references to objects passed into a constructor. As such, I advocate the use of pointers in this case even when null is undesirable.
Note: I do not have access to change the implementation of the hierarchy of classes (A,B,C) as they are generated code and I do not have access to change the generator.
In this case you may instead wrap the generated classes with better classes:
class AWrapper {
A a;
// custom implementation that encapsulates A
}
If null pointers are valid values that cannot be avoided, then such invariant is of course not possible. In such case, you must always check whether the pointer is null before indirecting through it:
if (B* b = foo.getB())
if (C* c = b->getC())
c->getN();
Another thing that you might consider is whether all these pointers are necessary. Perhaps it would be simpler if the classes contained each other instead of indirectly referring to one another.
You need to test all along the way:
A foo;
B* BPrt = foo.getB();
if (BPrt)
{
C* CPtr = BPrt->getC();
if (CPtr)
{
int n = CPtr->getN();
...
Here's how I solved the problem:
#include <iostream>
using namespace std;
class C {
private:
int _n;
public:
int getN() {return _n;}
};
class B {
private:
C* _c;
public:
C* getC() {return _c;}
};
class A {
private:
B* _b;
public:
B* getB() {return _b;}
};
int main(void);
int main() {
static B b;
static C c;
static A foo;
unsigned int n;
B *bPtr; C *cPtr;
/* --RECODE (CHAIN-CALL): foo.getB()->getC()->getN();-- */
bPtr = (B *) (foo.getB());
cPtr = (C *) (bPtr ? bPtr->getC() : 0);
n = (int) (cPtr ? cPtr->getN() : 0);
/* --USE (CAST) and (TERNARY) instead of (CHAIN-CALL)-- */
cout << n << endl;
return n;
}
If the classes cannot be changed then the checking could be done via a template:
template <typename T, typename A, typename ...Args>
auto recurse(T t, A a, Args... args)
{
if (!t)
throw std::exception{};
auto next = (t->*a)();
if constexpr (sizeof...(Args) > 0)
return recurse(next, args...);
else
return next;
}
Then call as follows:
recurse(&foo, &A::getB, &B::getC, &C::getN);
The problem is not with a pointer being null. That is in-fact good as it mostly crashes at runtime. What if it's not null but has been previously freed/deleted ? The usage will probably lead to Undefined Behaviour.
A better way would be to use references if you can:
class A
{
private:
B& _b;
public:
A(B& b): _b{b} {}
B& getB ()
{
return _b;
}
};
Or something like that. Then you at-least don't have anything dangling (unless you are also using pointers somewhere).
If you have to use pointers then use one of the smart-pointers - see if std::unique_ptr solves if for you. If not then for shared ownership use std::shared_ptr and so on. Also ensure the way you initialise objects don't lead to a default null there.
You can make sure that your pointers are always initialized, if possible:
class C {
private:
int _n = 0;
public:
int getN() {return _n;}
};
class B {
private:
static C default_c;
C* _c = &default_c;
public:
C& getC() {return *_c;}
};
C B::default_c; // An out-of-line static member definition is required.
class A {
private:
static B default_b;
B* _b = &default_b;
public:
B& getB() {return *_b;}
};
B A::default_b; // An out-of-line static member definition is required.
int main() {
A a;
std::cout << a.getB().getC().getN() << '\n';
}
Note that pointers make better members than references because the references break value semantics and make your class non-assignable.
Did you consider:
try {
foo.getB()->getC()->getN();
}
catch(...)
{
//Here you know something is Null
}
That seems the simplest safest,when dealing with existing code.
Related
Look at following code:
class A
{
protected:
int aa = 1;
};
class B : public A
{
private:
int bb = 2;
public:
int getbb() { return bb; }
};
class C : public A
{
private:
int cc = 3;
public:
int getcc() { return cc; }
};
int main()
{
std::vector<A> a;
B b;
C c;
a.push_back(b);
a.push_back(c);
a[0].getbb(); //getbb() unaccessible;
a[1].getcc(); //getcc() unaccessible;
}
A is the based class. B and C is the derived classes. I want to set a vector to hold either B or C, and use vector a to hold A. However, since a is a vector containing A's objects, I can't access methods in B and C. Is there anyway to make a[0].getbb() and a[1].getcc() work?
Your vector of A is not capable of holding Bs or Cs, because it stores A by value, resulting in object slicing when B or C is stored. In particular, this means that when you store B, only aa gets stored; bb gets sliced away.
In order to store subclasses without slicing use a container of pointers - preferably, of smart pointers.
This wouldn't help you access functionality specific to B or C without a cast. One way to solve this problem is to give virtual member functions for B's and C's functionality to A, and make calls through A-typed reference of B or C.
Not without invoking undefined behaviour.
The problem is that a.push_back(b) and a.push_back(c) do not append objects b and c to the vector. They create instances of A that hold only the "A parts". This is called object slicing.
So there is no object of type B and no object of type C in the vector.
You force the issue and make your code compile by doing something like
static_cast<B &>(a[0]).getbb();
but this just has undefined behaviour, since it treats a[0] as being of type B when it is really of type A. Which makes it a really bad idea. Although it will (probably) compile, it could do anything - and probably not what you expect.
If your vector contains A * rather than A it is possible. For example;
int main()
{
std::vector<A *> a;
a.push_back(new B);
a.push_back(new C);
B* b = dynamic_cast<B *>(a[0]);
if (b) // if a[0] actually points at a B ....
b->getbb();
else
complain_bitterly();
C *c = dynamic_cast<C *>(a[1]);
if (c)
c->getcc();
else
complain_bitterly();
}
Of course, doing this has practical trap doors as well - such as requiring class A having at least one virtual member. It would be better off to work with a polymorphic base, and override virtual functions.
In other words, your design is broken, so fix it so it doesn't somehow require you to morph an object to a different type.
An alternative to using pointers is to use a vector of std::reference_wrappers and polymorphic classes. Small example below:
#include <functional> // for std::reference_wrapper
#include <iostream>
#include <vector>
class A
{
public:
virtual void printme()
{
std::cout << "A" << std::endl;
}
virtual ~A() = default;
};
class B: public A
{
public:
void printme() override
{
std::cout << "B" << std::endl;
}
};
class C: public A
{
public:
void printme() override
{
std::cout << "C" << std::endl;
}
};
int main()
{
std::vector<std::reference_wrapper<A>> a;
B b;
C c;
a.emplace_back(b);
a.emplace_back(c);
a[0].get().printme(); // need to "get()" the raw reference
a[1].get().printme();
}
Live on Coliru
According the the cpp reference, there seems to be a way to achieve this by using dynamic_cast. You first need to make your vector a vector of pointers to the base class A. Then when accessing any element, you can check if it is a B* (or a C*) by checking the result of the dynamic_cast operator.
From the CPP reference:
dynamic_cast < new_type > ( expression )
... If the cast is successful, dynamic_cast returns a value of type new_type. If the cast fails and new_type is a pointer type, it returns a null pointer of that type...
Accordingly, you can do this:
std::vector<A*> a;
B b;
C c;
a.push_back(&b);
a.push_back(&c);
...
int i = something;
B* pB = dynamic_cast<B*>(a[i]); if(pB != nullptr) pb->getbb();
C* pC = dynamic_cast<C*>(a[i]); if(pC != nullptr) pC->getcc();
p.s: It is highly questionable as design approach though. The recommended OOP approach would be certainly to use a virtual method in the base class A and override it in B and C. But (hopefully) this answers the exact question as stated in the title.
If you're sure they're instances of B and C, use cast:
static_cast<B>(a[0]).getbb();
static_cast<C>(a[1]).getcc();
OK, you may also create a vector of A*:
std::vector<A*> as;
as.push_back(new B);
as.push_back(new C);
B* b = (B*) as[0];
b->getbb();
c->getcc();
Now you only have to remember about freeing objects with delete.
You may use "Type IDs":
class A {
// ...
virtual int getTypeID() { return 0; }
}
class B {
// ...
virtual int getTypeID() { return 1; }
}
// analogically for C
It's virtual but is in prototype of A
Now use:
switch(a.getTypeID()) {
case 0:
// It's normal A
break;
case 1:
// It's B
// ...
break;
case 2:
// It's C
// ...
break;
}
Apologize for the verbose title. I do not know how to express this succinctly.
class A
{
bool a1;
unsigned int a2 ;
virtual bool aFn1(unsigned int t_) = 0 ;
virtual void aFn2(unsigned int t_, bool val_) = 0 ;
A()
{
a1 = false ; a2 = 0 ;
};
}
Next:
#include <bitset>
#define MAX_SIZE 500
class B : public class A
{
private:
std::bitset<MAX_SIZE> _bmem;
public:
B() : A() {};
using A::aFn1 ;
virtual bool aFn1(unsigned int t_)
{
return _bemem[t_]
}
using A::aFn2;
virtual void aFn2(unsigned int t_, bool val_)
{
_bemem[t_] = val_ ;
}
}
Next:
#include "A.h"
#include "B.h"
std::vector<A*> * vecA;
vecA = new std::vector<B*> ;
But this last step does not work. clang complete tells me
assigning to std::vector<A*> * from incompatible type std::vector<B*>
But since B derives from A, this should be possible right? I have seen examples where people use
B bObj;
A *aObj = &bObj ;
So could you please tell me what mistake I am making?
The reason I go through all this, is because I have class C and class D, exactly like class B, where the only difference is that #define MAX_SIZE is different.
I do this because, I need a bitset of different sizes, to be used in different phases of the program. And bitset requires the number of elements it needs to store at compile time.
You are using far too many interfaces and pointers.
class A {
bool a1 = false;
unsigned int a2 = 0;
std::vector<bool> values;
bool aFn1(unsigned int t_) const { return values[t_]; }
void aFn2(unsigned int t_, bool val_) { values[t_] = val_; }
void set_size(size_t i){values.resize(i);}
A() = default;
static A of_size(size_t i){ A r; r.set_size(i); return r; }
};
then use a std::vector<A>.
If you 100 elements of size 500, do std::vector<A> v( 100, A::of_size(500) );
This code will do fewer allocations, use less memory, and have less indirection than your code. Using new is "code smell", often a sign you have made a mistake, unless you really need objects of extremely complex lifespan.
A std::vector<bool> values will be nearly as compact as a std::bitset<500>, and the difference is made up by the other pointers I eliminated.
You cannot make a std::vector<A*>* point to a std::vector<B*>*, those are disparate types.
What you can do is push B* into a std::vector<A*>:
std::vector<A*> vec;
B b;
vec.push_back(&b);
Of course you need to be careful about the lifetime of the pointers. You might want to use std::unique_ptr if the vector should manage the lifetime itself.
Also note that A needs a virtual destructor, otherwise it is undefined behaviour to delete a B* through an A*.
clang complete tells me assigning to std::vector<A*> * from incompatible type...
Clang tells you the truth.
But since B derives from A, this should be possible right?
Not right.
I have seen examples where people use
B bObj;
A *aObj = &bObj ;
Those examples are correct. They work because A is a parent of B. A pointer of a child class can be converted to a pointer to a parent class.
So could you please tell me what mistake I am making?
You're trying to assign a pointer to std::vector<B*> into a pointer to std::vector<A*>. std::vector<A*> is not a parent of std::vector<B*>. In terms of inheritance they are entirely unrelated classes. Pointer to a type cannot be converted to a pointer to an unrelated type.
This boils down to
std::vector<Base*> *v = new std::vector<Derived*>;
But std::vector<Base*> and std::vector<Derived*> aren't compatible types, for the same reason that you can't use an array of Derived* as an array of Base*.
For example, in the above, what should happen if you write v->push_back(new Base())? You can't have a Base* in your vector of Derived*.
For a good explanation of the issues involved in treating a Derived* as a Base*, see also the reasoning behind this answer to "Converting std::function<void(Derived*)> to std::function<void(Base*)>", which is the same issue in a different guise.
I was wondering how protect a non const pointer member from an object throught a const method. For example:
class B{
public:
B(){
this->val=0;
}
void setVal(){
this->val = 2;
}
private:
int val;
};
class A{
public:
A():b(new B){}
void changeMemberFromConstMethod() const{
this->b->setVal();
}
private:
B * b; // how to protect data pointed in A::changeMemberFromConstMethod
}
Is it possible to "protect" A::b data pointed from his method?
After many research on web, no satisfied reponse found yet.
Thanks for your help.
Something like this, perhaps:
template <typename T>
class deep_const_ptr {
T* p_;
public:
deep_const_ptr(T* p) : p_(p);
T* operator->() { return p_;}
const T* operator->() const { return p_;}
};
class A {
deep_const_ptr<B> b = new B;
};
deep_const_ptr behaves like a const T* const pointer in A's const methods, and like T* in non-const methods. Fleshing the class out further is left as an exercise for the reader.
If you change the member of A from
B* b;
to
B b;
then you will get the expected behavior.
class A{
public:
A() : b() {}
void changeMemberFromConstMethod() const{
this->b.setVal(); // This will produce a compiler error.
}
private:
B b;
}
The problem you have is that a const method makes all the member variables const. In this case however, it makes the pointer const. Specifically, it's as if all you have is B * const b, which means a constant pointer to a (still) mutable B. If you do not declare your member variable as const B * b, (that is, a mutable pointer to a constant B), then there is no way to protect from this behavior.
If all you need is a const B, then by all means, define A like this:
class A {
public:
A() : b(new B) {}
// This WILL give an error now.
void changeMemberFromConstMethod() const { b->setVal(); }
private:
const B* b;
}
However, if other methods of A mutate B, then all you can do is make sure that B does not get mutated in your const methods of A.
Try using the following general approach, to protect the const-ness of objects referenced via pointers, in this situation.
Rename B *b
B *my_pointer_to_b;
And change the initialization in the constructor accordingly.
Implement two stubs:
B *my_b() { return b; }
const B *my_b() const { return b; }
Replace all existing references to b with my_b(), in the existing code. Going forward, in any new code, always use my_b() to return the pointer to b.
Mutable methods will get a non-const pointer to B; const methods will get a const pointer to B, and the extra step of renaming makes sure that all existing code is forced to comply with the new regime.
I was wondering how you can do polymorphism with references, as opposed to pointers.
To clarify, see the following minimal example:
class A;
class B {
public:
A& a; ///////////////// <- #1
B();
void doStuff();
};
class A {
public:
virtual void doSmth() = 0;
};
void B::doStuff() {
a.doSmth();
}
class A1 : public A {
public:
void doSmth() {
}
};
B::B() : a(
* ////////////// <- #2
(new A1) /////////// <- #3
) {
}
This compiles and works, but as the most important point here is that a in line #1 is a reference, so in order to be able to use it polymorphically (is that an actual word?), as shown in line #3 I have to "convert a pointer to a reference" by dereferencing it.
This strikes me as a bit odd, and I was wondering if there is a better (in the sense of cleaner) way. Is it just me?
Rationale
It would be great if I didn't need a new at all, but when declaring (!) B I have no clue how to create an instance of A1 (!) as A is a forward declaration -- A1 is implemented in the same compilation unit as B. Still, is there a real need for dynamic memory allocation in this case? How would you do this?
Sorry for the slightly twofold question.
Edit
Note: B is huge (and I cannot make a template class of it), and will go out of scope precisely when the program terminates -- a is small and makes two big modules talk to each other, it will be needed as long as the instance of B lives (there is only one).
Edit 2
I just realised, that since both A and B are effectively singletons, I can simply create a static instance of A1 in the compilation unit of B, avoiding dynamic memory allocation (even if there were two Bs they could easily use the same instance of A). To be fair, I did not post this as answer, but will accept the answer that prompted me to come up with this solution.
There's nothing odd. Polymorphisms works both for pointers and references:
struct Base { };
struct Derived : Base;
void foo(Base &);
int main() {
Derived x;
foo(x); // fine
}
You're conflating this with another issue, namely creating a reference to a dynamic object:
T * pt = new T;
T & rt = *pt;
T & x = *new T; // same effect
Note that it's generally very bad style to track a dynamic object only by reference, because the only way to delete it is via delete &x;, and it's very hard to see that x needs cleaning up.
There are two immediate alternatives for your design: 1) make a a member object in B, or 2) make a a shared_ptr<A> or unique_ptr<A> and change the initalizer to a(new A1). It all depends on whether you actually need the polymorphic behaviour, i.e. if you have other constructors for B which assign a different derived class to a other than A1.
This is indeed a bit odd. If you want a member-variable of type A1 (rather than a reference), why not just rearrange your code so that the definition of A1 appears before the definition of B?
Still, is there a real need for dynamic memory allocation in this
case?
No. Just define A1 first and then make it a normal member of B.
Polymorphism works just fine with both references and pointers.
Erm, is this not sufficient?
#include <iostream>
struct A;
struct B
{
B(A& a);
void foo();
A& _a;
};
struct A
{
virtual void foo() =0;
};
struct A1 : public A
{
virtual void foo() { std::cout << "A1::foo" << std::endl; }
};
B::B(A& a) : _a(a) {}
void B::foo() { _a.foo(); }
int main(void)
{
A1 a; // instance of A1
B b(a); // construct B with it
b.foo();
}
Still, is there a real need for dynamic memory allocation in this case?
Either the dynamic memory allocation or injecting the reference into B's ctor.
It's no stretch to imagine why references can work polymorphically like pointers (not to mention references are often implemented as pointers anyway). Here's a quick example:
class Base {
public:
virtual void something() { }
};
class Derived : public Base {
public:
void something() { }
};
Base& foo() {
static Derived d;
return d;
}
foo().something(); // calls Derived's something
Also why are you allocating dynamic memory for a reference? You probably shouldn't be using a reference in this case at all. Also, writing classes with reference members effectively prevents assignment (as I heard someone say quite well).
I realize this is a really old post but there is another option you have for handling references for dynamically allocated objects. You can assign a reference to the dynamically allocated object. Below is some dummy code to give you an idea of how this works.
struct A
{
int b;
virtual void print();
A(int val):b(val) {}
};
struct A_child:public A
{
A_child(int val):A(val) {}
void print();
};
void A:print()
{
cout<<"parent\n";
}
void A_child:print()
{
cout<<"child\n";
}
struct test_ref
{
A *& ref;
test_ref(A * ptr) : ref(ptr)
}
int main()
{
test_ref parent(new A(12));
parent.ref->print();
test_ref child(new A_child(15));
child.ref->print();
}
To be honest I am not certain when this is a good idea. I just wanted to show an alternative approach where you dont have to dereference the dynamically allocated memory when initializing an object.
I am also pretty certain dynamically allocating a pointer while initializing a class where the pointer is stored as a reference pointer will probably lead to a memory leak unless you can delete the reference pointer.
I have an (for C++ programmers better than me) simple problem with classes and pointers.
I thought about posting example code describing my problem but I found it easier to just explain it in words.
Assuming I have three classes:
Class A: The main class - it contains an instance of both B and C.
Class B: This class contains a method that outputs some string, call it Greet().
Class C: This one has a method too, but that method has to call Greet() in the instance of B that is located in class A. Let's name it DoSomethingWithB()
So the program starts, in the main function I create an instance of A. A, again, creates instances of B and C. Then, A calls C.DoSomethingWithB();.
And there my problem begins: I can't access B from inside C.
Obviously, I will need to pass a pointer to B to the DoSomethingWithB() function so that I can call B.Greet() from inside C
Long explanation, short question: How do I do this?
Example code incoming:
#include <iostream>
using namespace std;
class B
{
public:
void Greet( )
{
cout<<"Hello Pointer!"<<endl;
}
};
class C
{
public:
void DoSomethingWithB( )
{
// ... b.Greet( ); Won't work obviously
}
};
class A
{
public:
B b; // Not caring about visibility or bad class/variable names here
C c;
void StartTest( )
{
c.DoSomethingWithB( );
}
};
int main( )
{
A mainInstance;
mainInstance.StartTest();
}
Wouldn't you simply pass a pointer or reference to he B object?
class C
{
public:
void DoSomethingWithB( B& b)
{
b.Greet( ); // will work fine
}
};
class A
{
public:
B b; // Not caring about visibility or bad class/variable names here
C c;
void StartTest( )
{
c.DoSomethingWithB( b);
}
};
If the DoSomethingWithB() function won't modify the passed in B instance, you should mark the reference const so it can be called with a const B object (for example if the owning A object happens to be const):
void DoSomethingWithB( B const& b);
You have a few options for how to pass the B object to the function:
as a reference (void DoSomethingWithB( B& b)) which will let the function modify the passed in object. Changes will be refelected in the object that's passed in.
as a const reference (void DoSomethingWithB( B const& b)) which won't let the function modify the passed in object (unless the constness is cast away - something which can lead to undefined behavior if done on an object the is truely const)
as a pointer or const pointer to a B object (void DoSomethingWithB( B* b) or void DoSomethingWithB( B const* pb) ). These have similar performance to passing by reference, but the function could be passed a NULL pointer which needs to be dealt with properly (by not dereferencing it in that case). Also, the call of the function would need to change slightly to pass the address of the B object:
c.DoSomethingWithB( &b);
as a pass-by-value parameter (void DoSomethingWithB( B b)). This has difference that the function can do whatever it likes with theo bject passed in and it won't affect the originally passed object since the function is dealing with a copy. The disadvantage is that passing the parameter causes a copy to be made which might be expensive. You could also pass in a const value, but there's little to recommend that over passing a const reference.
Note that when chosing the parameter passing method, you should first chose based on the sematics of what you need the function to do (or not do). Worry about efficiency later. Always first design and code for correctness - worry about efficiency only after you have the design and code correct.
Change the functions to the following:
void DoSomethingWithB(B& b)
{
b.Greet();
}
... and in A ...
c.DoSomethingWithB(b);
You can do it just as you said -- pass a pointer (or a reference) to B in to DoSomethingWithB():
class C
{
public:
void DoSomethingWithB(B & bInstance)
{
bInstance.Greet( ); // should work fine!
}
};
Then you'll invoke it like so:
class A
{
public:
B b; // Not caring about visibility or bad class/variable names here
C c;
void StartTest( )
{
c.DoSomethingWithB( b );
}
};
I'd suggest using the reference approach here rather than a pointer, since:
Your object is an automatic class member, and
Passing a null B object into the function is not meaningful in this case.
In class C, declare the method DoSomethingWithB() like this:
void DoSomethingWithB( B* b )
{
b->Greet();
}
And in class A call it like this:
void StartTest()
{
c.DoSomethingWithB( &b );
}
Since you mentioned pointers, I answered using pointers. In C++ however, you should try to use const references whenever you can. That would of course require a small change to the existing code:
void DoSomethingWithB( const B& b )
{
b.Greet();
}
// and
void StartTest()
{
c.DoSomethingWithB( b );
}
I can't access B from inside C
Instead of having C call methods in B, why not have C return information to the caller so it can do the operation?
When I hit these I've found it's because I've got my classes organized poorly. Usually if I rethink them the difficulty disappears with a new organization.
class C
{
public:
C (B & b) : b(b) {}
void DoSomethingWithB( )
{
// ... b.Greet( ); Use b;
}
private:
B & b;
};
class A
{
public:
B b; // Declare b before c!
C c;
A() : c (b) {}
void StartTest( )
{
c.DoSomethingWithB( );
}
};