473,785 Members | 2,851 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Object Composition & Returning References....

I want to achieve the following behaviour but I am having trouble
getting there...bare with me im knew to c++ , so its probably rather
trivial!

To have a class ClassA, and composed within this class is an instance
of another class, ClassB.
I want to have a method getClassB that returns a reference to the
instance of ClassB composed within ClassA.
So when a client calls getClassB they are supplied with a reference to
the instance of ClassB composed within ClassA, so that any
modifications that the client makes to this reference are mirrored in
the instance composed within ClassA.

So far I have constructed ClassA, ClassB, and managed to have an
instance of ClassB composed within ClassA.

My problem is with the "getClassB" method. I have only managed to be
able to return a pointer to the instance of ClassB composed within
ClassA. I want to be able to return a reference (&) not a pointer (*).

The instance of ClassB composed within ClassA is initialised in the
constuctor using
classB = new ClassB(9);
so I have to store it within the class as a pointer i.e.
class ClassA
{ public:
ClassA();
~ClassA();
ClassB* getClassB();

private:
ClassB *classB;
};
then when i go to implement the getClassB method I cannot figure out
how to return a reference.

Is there a way of returning a reference givin that I store classB as a
pointer?
Or do I need to store classB differently? I have tried derefenceing
the pointer return by the "classB = new ClassB(9);" and storing it
explicitly but this didnt seam to work.

The full listing of the code is below with a test file, I want to
maintain the same behaviour as is present at the moment, but using
references instead of pointers in the getClassB method.

That is i want to replace

ClassB* ClassA::getClas sB()
{ return classB;
}

with

ClassB& ClassA::getClas sB()
{ return classB;
}

any help/pointers greatly appreciated.

pat
----------------------------------------------------------
//Main.cpp

#include <iostream>
#include <cstdlib>
#include "ClassA.h"
#include "ClassB.h"

using namespace std;

int main(int argc, char *argv[])
{
ClassA a;
ClassB *b = a.getClassB();
cout << "a.getClass B() = " << *(a.getClassB() ) << "\n";
cout << "b = " << *b << "\n";

b->setValue(0);

cout << "\n\nAfter : b.setValue(0)\n ";
cout << "a.getClass B() = " << *(a.getClassB() ) << "\n";
cout << "b = " << *b << "\n";

a.getClassB()->setValue(4);
cout << "\n\nAfter : a.getClassB().s etValue(4)\n";
cout << "a.getClass B() = " << *(a.getClassB() ) << "\n";
cout << "b = " << *b << "\n";

system("Pause") ;
return 0;
}

----------------------------------------------------------
//ClassA.h

#ifndef CLASSA_H
#define CLASSA_H

#include "ClassB.h"

using namespace std;

class ClassA
{ public:
ClassA();
~ClassA();
ClassB* getClassB();

private:
ClassB *classB;
};

#endif

----------------------------------------------------------
//ClassA.cpp

using namespace std;

#include "ClassA.h"
#include "ClassB.h"

ClassA::ClassA( )
{ classB = new ClassB(9);
}

ClassA::~ClassA ()
{ delete classB;
}

ClassB* ClassA::getClas sB()
{ return classB;
}

----------------------------------------------------------
//ClassB.h

#ifndef CLASSB_H
#define CLASSB_H
#include <iostream>

using namespace std;
class ClassB
{ friend ostream& operator<<(ostr eam& , const ClassB&);

public:
ClassB(int value);
void setValue(int value);

private:
int value;
};

#endif

----------------------------------------------------------
//ClassB.cpp

#include "ClassB.h"

ClassB::ClassB( int value)
{ (*this).value = value;
}

void ClassB::setValu e(int value)
{ (*this).value = value;
}

ostream& operator<<(ostr eam& output, const ClassB& object)
{ output << object.value;
return output;
}
----------------------------------------------------------
Jul 22 '05 #1
4 1779

"Patrick" <go***********@ yahoo.co.uk> wrote in message
news:94******** *************** ***@posting.goo gle.com...
I want to achieve the following behaviour but I am having trouble
getting there...bare with me im knew to c++ , so its probably rather
trivial!

To have a class ClassA, and composed within this class is an instance
of another class, ClassB.
I want to have a method getClassB that returns a reference to the
instance of ClassB composed within ClassA.
So when a client calls getClassB they are supplied with a reference to
the instance of ClassB composed within ClassA, so that any
modifications that the client makes to this reference are mirrored in
the instance composed within ClassA.

So far I have constructed ClassA, ClassB, and managed to have an
instance of ClassB composed within ClassA.

My problem is with the "getClassB" method. I have only managed to be
able to return a pointer to the instance of ClassB composed within
ClassA. I want to be able to return a reference (&) not a pointer (*).

The instance of ClassB composed within ClassA is initialised in the
constuctor using
classB = new ClassB(9);
Do you have a good reason for doing it this way? Its generally better to
avoid pointers, if you can.
so I have to store it within the class as a pointer i.e.
class ClassA
{ public:
ClassA();
~ClassA();
ClassB* getClassB();

private:
ClassB *classB;
};
then when i go to implement the getClassB method I cannot figure out
how to return a reference.


Simple

ClassB& getClassB() { return *classB; }

john
Jul 22 '05 #2
Thanks for the reply

I had implemented getClassB as you suggested, but when i was doing the
following in the code that called it

ClassB b = a.getClassB();

I understand now that the "copy" constructor was being used here,
right?

How can i (or is it possible to) implement the getClassB() method s.t.
when i do the following

ClassB b = a.getClassB();

i am not using the copy constructor, and "b" refers to the instance of
ClassB composed within ClassA, not a copy of it.
Do you have a good reason for doing it this way? Its generally better to
avoid pointers, if you can.


Yes i think so, but could be wrong, this is just a toy example to help
me figure out how to get it working.

My ClassA will store a Vector of (references to) ClassB objects.
ClassA will allow the client add and delete ClassB objects from this
Vector.
And I need to be able to return a reference to this Vector from ClassA
to the client.
So I was trying to figure out how to get it working with just an
instance of ClassB composed within ClassA, then i will hopefully
understand how to get it working with a Vector containing instances of
ClassB. Maybe its just as easy as my example at the moment.

much appreciated.

pat
Jul 22 '05 #3

"Patrick" <go***********@ yahoo.co.uk> wrote in message
news:94******** *************** ***@posting.goo gle.com...
Thanks for the reply

I had implemented getClassB as you suggested, but when i was doing the
following in the code that called it

ClassB b = a.getClassB();

I understand now that the "copy" constructor was being used here,
right?

How can i (or is it possible to) implement the getClassB() method s.t.
when i do the following

ClassB b = a.getClassB();

i am not using the copy constructor, and "b" refers to the instance of
ClassB composed within ClassA, not a copy of it.


Use a reference

ClassB& b = a.getClassB();

but remember that you cannot 'reseat' references, i.e. if later you do

b = a2.getClassB();

that will not make b refer to the ClassB object in a2, instead it will copy
the a2 ClassB to the a ClassB (which b will still refer to).

If you think you might need to change where a variable refers to, you are
better of using pointers than references.

john
Jul 22 '05 #4
Just for the record, this is what i was trying to do.
It looks right, it seems to work right, so hopefully its gotta be
right, right?

pat
------------------------------------------------------------------------
//main.cpp
#include <iostream>
#include <cstdlib>
#include "ClassA.h"
#include "ClassB.h"

using namespace std;

int main(int argc, char *argv[])
{
ClassA a;
ClassB b1(1);
ClassB* b2 = new ClassB(2);
ClassB b3(3);

//adding element to vector composed within instance of ClassA
a.addElement(b1 );

//making a reference to vector composed within instance of ClassA
vector<ClassB>& classBVec2 = a.getClassBVec( );

//altering an object in the vector composed within instance of ClassA,
//via reference to it
classBVec2[0].setValue(11);

//altering the vector composed within instance of ClassA,
//via reference to it
classBVec2.push _back(*b2);

//altering the vector composed within instance of ClassA,
//via reference to it
classBVec2.push _back(b3);

system("Pause") ;
return 0;
}
------------------------------------------------------------------------
//ClassA.h

#ifndef CLASSA_H
#define CLASSA_H
#include <vector>

#include "ClassB.h"

using namespace std;

class ClassA
{ public:
ClassA();
void addElement(Clas sB& element);
vector<ClassB>& getClassBVec();

private:
vector<ClassB> classBVec;
};

#endif

------------------------------------------------------------------------
//ClassA.cpp

using namespace std;
#include "ClassA.h"

ClassA::ClassA( )
{
}

void ClassA::addElem ent(ClassB& element)
{ classBVec.push_ back(element);
}

vector<ClassB>& ClassA::getClas sBVec()
{ return classBVec;
}

------------------------------------------------------------------------
//ClassB.h

#ifndef CLASSB_H
#define CLASSB_H
#include <iostream>

using namespace std;
class ClassB
{ friend ostream& operator<<(ostr eam& , const ClassB&);

public:
ClassB(int value);
void setValue(int value);

private:
int value;
};

#endif

------------------------------------------------------------------------
//ClassB.cpp

#include "ClassB.h"

ClassB::ClassB( int value)
{ (*this).value = value;
}

void ClassB::setValu e(int value)
{ (*this).value = value;
}

ostream& operator<<(ostr eam& output, const ClassB& object)
{ output << object.value;
return output;
}
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
3832
by: pablo | last post by:
Dear NewsGroupers, I am relatively new to OOP and cannet get my head around this problem. I have two classes. Class Child extends Parent. There is no constructor for the Child class. So when I create a child object the constructor for the parent object is called. That works fine. But now I have the problem that I want to add an already existing Parent object to create a new Child object. How can this be done?
7
20375
by: Pablo J Royo | last post by:
Hello: i have a function that reads a file as an argument and returns a reference to an object that contains some information obtained from the file: FData &ReadFile(string FilePath); But , for example, when the file doesnt exists, i should not return any reference to a bad constructed object, so i need something as a NULL reference object. I suppose i could return a pointer instead, but i have some code written with references which...
12
3293
by: Olumide | last post by:
I'm studying Nigel Chapman's Late Night Guide to C++ which I think is an absolutely fantastic book; however on page 175 (topic: operator overlaoding), there the following code snippet: inline MFVec operator+(const MFVec& z1, const MFVec& z2) // Global function { MFVec res = z1; res += z2 return res; // WHY???
6
1509
by: Matthias Kaeppler | last post by:
Hello, during a discussion on a C++ internet forum, some question came up regarding references and the lifetime of the objects they alias. I can't find any clear wording on that in the draft standard. Example 12.2 in the standard document illustrates that temporaries bound to references-to-const live as long as the reference does. But does it e.g. matter if the temporary was created in scope of a function body and has to outlive the...
1
1598
by: Tony Johansson | last post by:
Hello experts! I know it's easy to override when you have inheritance. But if you instead use object composition having a pointer to a class X. If you want to override when having this object composition how is that done. Give some easy example if you have some.
4
14451
by: Frederik Vanderhaegen | last post by:
Hi, Can anyone explain me the difference between aggregation and composition? I know that they both are "whole-part" relationships and that composition parts are destroyed when the composition whole is destroyed. Under a "whole-part" relationship I understand the following: the whole can't exists without the parts, but can the parts exist without the hole? f.e.: a car can't exist without an engine private engine _Engine
11
3846
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you experts. I would like to produce Javascript classes that can be "subclassed" with certain behaviors defined at subclass time. There are plenty of ways to do this through prototyping and other techniques, but these behaviors need to be static and...
11
1811
by: Xiaoshen Li | last post by:
Dear Sir, I am a little puzzled about a function returning a class object, for example, suppose I hava a class Money and a method: Money lastYear(Money aMoney) { Money tempMoney; ... return tempMoney;
2
14827
by: Gary Wessle | last post by:
Hi what is the difference "in code writing" between aggregation and composition? is the following correct? aggregation (life time of both objects are independent). class A{ /* ... */ }; class B{ A& a; /* ... */};
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10152
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9950
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8974
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5381
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4053
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3650
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2880
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.