Jump to content

Defining Classes In Terms Of Each Other?

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Raja Sekharan

Raja Sekharan

    Newbie

  • Members
  • PipPip
  • 13 posts
Hi,

Is it possible, safe, good practice to define two classes in terms of each other (example: a point to a object of other class as a member in both classes) C++.

Raja Sekharan

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
I'm not sure exactly what you mean, but it is fairly common to have member data of one class be another class. As long as you don't create a loop where A has data member B, and B has data member A, as that could consume all your memory when you create a variable of type A or B.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
julmuri

julmuri

    Programmer

  • Members
  • PipPipPipPip
  • 139 posts

Raja Sekharan said:

Hi,

Is it possible, safe, good practice to define two classes in terms of each other (example: a point to a object of other class as a member in both classes) C++.

Raja Sekharan

Its not bad practice, but theres few things you need to take care of.
If your app is multithreaded you need to make sure that the shared object is thread safe.
If your not familiar with the topic you should google it.
Heres few articles you might want to read:
Yolinux tutorial on pthreads
Codeproject article on thread synchronization

You also need to manage the lifetime, as in who 'owns' the object and when it should be destoyed.
First solution that comes to mind is to make the shared object reference counted.
Again google is your friend, but heres somethin on the topic:
Wiki to rescue! (:
Dr.Dobb's article on atomic reference counting pointers

You can find alot wrappers from web for both synchronization and reference counting so go look around. :p
Hope this helps