473,699 Members | 2,433 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Class as member of another class question.

Consider the following simplified hypothetical code:

#include <iostream.h>

class rabbit
{
public:
rabbit() {x = 3; y = 3; /*code here to set field[x][y] to 1*/}
void runtocage();
int x;
int y;
}

void rabbit::runtoca ge()
{
//code here to set field[x][y] to 0 and field[0][0] to 1
}

class garden
{
public:
void monsterattack() ;
rabbit fluffy;
bool field[5][5];
}

void garden::monster attack()
{
fluffy.runtocag e();
cout << "Ahh!!";
}

//End of code segment

This not at all what I'm really working on...I'm working on a linked
list for something, but what I show here is what is almost necessary
for what I'm doing...just thought the rabbit/garden thing would be cute
and clearly show what I'm wondering about...

Now for the question:
In the two places I have commented in the rabbit code, how can I do
what I wrote?

Could I add a member variable to rabbit that is a pointer to a garden
(garden * homesweethome; for instance) and give it the address of the
garden in the rabbit constructor when the rabbit is created in the
garden? (in garden code: "rabbit fluffy(this);" instead of "rabbit
fluffy;" and then change the rabbit constructor to: "rabbit(gar den
home) {x = 3; y = 3; homesweethome = home; homesweethome->field[x][y] =
1;}" then do some similar code as that last command in the runtocage()
function to change the "field"...)

Won't that cause a compile error, however, because whichever class I
put before the other, the compiler will tell me it doesn't know what
one of them is when it is referred to in the other.

I'm probably missing something simple...there are some basic things
I've missed in the book's I've read and the classes I've taken...
Thanks for your time,
John

Jul 22 '05 #1
6 1732
"SearedIce" <jo************ @yahoo.com> wrote...
Consider the following simplified hypothetical code:

#include <iostream.h>
I sincerely hope this is hypothetical. You aren't using <iostream.h> in
your real code, are you?

class rabbit
{
public:
rabbit() {x = 3; y = 3; /*code here to set field[x][y] to 1*/}
What's field[x][y]? And prefer initalisation over assignment. It's in
the FAQ.
void runtocage();
int x;
int y;
} ;

void rabbit::runtoca ge()
{
//code here to set field[x][y] to 0 and field[0][0] to 1
What's field[x][y]?
}

class garden
{
public:
void monsterattack() ;
rabbit fluffy;
bool field[5][5];
Ah, *that* field?
} ;

void garden::monster attack()
{
fluffy.runtocag e();
cout << "Ahh!!";
}

//End of code segment

This not at all what I'm really working on...I'm working on a linked
list for something,
Really? Why? There is 'std::list', just use it...
but what I show here is what is almost necessary
for what I'm doing...just thought the rabbit/garden thing would be cute
and clearly show what I'm wondering about...
Cute? Are you trying to appeal to our inner children?

Now for the question:
In the two places I have commented in the rabbit code, how can I do
what I wrote?
Pass the 'field' as an argument.
Could I add a member variable to rabbit that is a pointer to a garden
(garden * homesweethome; for instance) and give it the address of the
garden in the rabbit constructor when the rabbit is created in the
garden?
Sure.
(in garden code: "rabbit fluffy(this);" instead of "rabbit
fluffy;" and then change the rabbit constructor to: "rabbit(gar den
home) {x = 3; y = 3; homesweethome = home; homesweethome->field[x][y] =
1;}" then do some similar code as that last command in the runtocage()
function to change the "field"...)
Something like that...
Won't that cause a compile error, however, because whichever class I
put before the other, the compiler will tell me it doesn't know what
one of them is when it is referred to in the other.
Read about "circular references" and "forward declarations".
I'm probably missing something simple...there are some basic things
I've missed in the book's I've read and the classes I've taken...


Read the book again, take the classes again.

V
Jul 22 '05 #2
On design: The class rabbit shouldn't have any knowledge of the
garden. What if you made another class called LooneyTunes where you
wanted to use a rabbit? The runtocage method should be a part of
another class or method which dictates how objects in the garden act,
and the garden class should provide methods to move objects within
itself.

Compiler errors will occur in the above scenario because you have a
circular reference. Rabbit is defined in terms of Garden, and Garden
is defined in terms of Rabbit. The compiler will recursively keep
searching for the definition of the class until it chokes.

The solution is to make sure each class has proper accessor methods
(get/set) for the private variables. Then, create another class that
then uses both rabbit and garden; GardenManager for example. Or,
design rabbit so it has no need to know anything about garden, and make
garden control all the logic for "runtocage" method.

There are multiple solutions to what you want to do, but I think your
example is obscuring what you're trying to do with a linked list.

I'm not clear on how you need this type of logic for a linked list,
though. The list needs no special knowledge of the type of objects its
storing. Please do some research on the Standard Template Library's
vector class (and other container classes) if you need some inspiration
for your studies. Otherwise, reread the books! ;-) We've all been
there!

Jul 22 '05 #3
On 17 Jan 2005 19:49:01 -0800, SearedIce <jo************ @yahoo.com> wrote:
Could I add a member variable to rabbit that is a pointer to a garden
(garden * homesweethome; for instance) and give it the address of the
garden in the rabbit constructor when the rabbit is created in the
garden? (in garden code: "rabbit fluffy(this);" instead of "rabbit
fluffy;" and then change the rabbit constructor to: "rabbit(gar den
home) {x = 3; y = 3; homesweethome = home; homesweethome->field[x][y] =
1;}" then do some similar code as that last command in the runtocage()
function to change the "field"...)
yes, and i would make it a reference instead of a pointer, because then
you do not need to worry about the NULL-case.
however, using a reference makes impossible the use of constructor which
does not initialize the reference.

Won't that cause a compile error, however, because whichever class I
put before the other, the compiler will tell me it doesn't know what
one of them is when it is referred to in the other.

I'm probably missing something simple...


yes :)
use a forward declaration.
i.e. in rabbit.h write:

class garden;
class rabbit
{
public:
rabbit(garden& g);
/*...*/
garden& mGarden;
};

and analogous in the header file for garden.

--
have a nice day
ulrich
Jul 22 '05 #4
Alright...thank s for your effort.
Can anyone recommend a good book on object-oriented design? I guess
I've passed the knowledge level of the C++ stuff I have and need
something with a more careful author.
About why I'm making my own list: I'm the type of person that needs to
know how/why something works...also I can have more control. Not to
mention, I can show off to friends...well, at least the ones that
program...
Also, I'm not programming as a profession...ju st a hobby...so, I have
the time to do stuff like make stuff on my own and not just use the
built-in stuff...it's more fun this way.
~John

Jul 22 '05 #5
"SearedIce" <jo************ @yahoo.com> wrote...
Alright...thank s for your effort.
Can anyone recommend a good book on object-oriented design?
I used (and liked at the time) "Advanced C++" by J.Coplien. It is a bit
old (1991?), but helped me a great deal. Check it out.

Also, there is a newsgroup comp.object, where you can definitely find more
concentrated knowledge about OOD. Books included.
I guess
I've passed the knowledge level of the C++ stuff I have and need
something with a more careful author.
About why I'm making my own list: I'm the type of person that needs to
know how/why something works...also I can have more control. Not to
mention, I can show off to friends...well, at least the ones that
program...
Also, I'm not programming as a profession...ju st a hobby...so, I have
the time to do stuff like make stuff on my own and not just use the
built-in stuff...it's more fun this way.


Write a compiler. If it's any good, your friends will be green with envy.

V
Jul 22 '05 #6
> Can anyone recommend a good book on object-oriented design?
Design Patterns
by Eric Gramma, et al

A really good book you shouldn't be without! A must for your bookshelf.

Jul 22 '05 #7

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

Similar topics

4
2495
by: Jian H. Li | last post by:
Hello, What's the essential differences between the two ways of "class::member" & "object.member"(or object_pointer->member)? class C{ public: void f() {} int i; };
3
3600
by: DanielBradley | last post by:
Hello all, I have recently been porting code from Linux to cygwin and came across a problem with static const class members (discussed below). I am seeking to determine whether I am programming non-standard C++ or if the problem lies elsewhere. To summarize static const class members are not being accessed properly when accessed from a DLL by another external object file (not within the DLL). It only occurs when the static const...
7
2127
by: Lionel B | last post by:
Greetings. The following code compiles ok and does what I'd expect it to do: ---------- START CODE ---------- // test.cpp
13
2727
by: jt | last post by:
Being a newbie in C++ and comming from C, I can't find information on how to access a class member function outside its class. Below is a snippet of the class and its member function: look at "AddCallPages" ============================================================= class CPsnstatuspttView : public CFormView { protected: // create from serialization only CPsnstatuspttView();
1
1845
by: Matthias Kaeppler | last post by:
Sorry if this has been discussed before (I'm almost certain it has), but I didn't know what to google for. My problem is, I have a class, a gtkmm widget, and I want it to serve as a base class now, but I'm not sure if I'm taking the proper steps in order to not break the whole class. Are there any guidelines what I have to watch out for? One question would e.g. be:
2
10756
by: Chi Tang | last post by:
Hi, I have 2 questions: How to call a class member function from another class and these 2 classes are in the same namespace? Also, how to use another project's dialog box and this 2 projects are in the same VS.NET solution?
0
1433
by: Sebastian Hiller | last post by:
Hello, i'm new to .Net (i'm using VB as language and i'm working in the code-behind mode) and i can't solve the following problem: I have a WebForm and want to Add a UserControl (classname:QuestionControl) as many times as there are rows in a DataTable (also named Questions) in a DataSet. But this UserControl is ,for reasons of structuring, not a member of the WebForm Object in which it should be displayed, it is member of another class...
2
2313
by: pookiebearbottom | last post by:
Just trying to learn some things about templates. Was wondering how boost::tupple really works, but the headers were a bit confusing to me. I know you get do something like the following, just want to know how it works with the overloading of get<>(). boost::tupple<int,doubletup(1,2.0); double d=tup.get<2>(); // equal 2.0 // simple set up,
4
2406
by: Steve Goldman | last post by:
Even asking this question probably demonstrates that I have a fundamental misunderstanding of how values and references work in C#, but here goes: I'd like to assign a reference to an arbitrary class member to another class member, so that I can later mutate the stored reference. I'd like to use this for an undo function - basically, when you make a change to a class member value, you call SaveMemberValue() to store the reference and...
20
4037
by: tshad | last post by:
Using VS 2003, I am trying to take a class that I created to create new variable types to handle nulls and track changes to standard variable types. This is for use with database variables. This tells me if a variable has changed, give me the original and current value, and whether the current value and original value is/was null or not. This one works fine but is recreating the same methods over and over for each variable type. ...
0
9174
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9034
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...
1
8914
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6534
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5874
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4376
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
4629
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3057
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
3
2009
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.