We help IT Professionals succeed at work.

simple question...(contained classes)

tamargooch
tamargooch asked
on
Hi,
I'm a cs student, and i'm taking my first c++, and oop course. my question is :
assuming i have contained classes, for example:
class a
{
public:
  void foo(){...}
}
class b
{
public:
  void foo(){...}
}

the question is: is it possible for a function in b
to access a public function in a?
something like :
class b
{
public:
 void print(){Rect::print()}
}

when i tried it, the vc++ told me that the outer class is undefined in the inner class' function...

Thanks,
Tamar.
Comment
Watch Question

Commented:
Again, think you made a typo or something. Your example doesn't contain any nested classes.

Kind regards,
nmeat
The answer is yes. How you do it depends on what you mean by "nested" - do you mean contained classes e.g.

class b
{
  a c;
...
}

or derived classes e.g.

class b : public a
{
...
}

LDC

Commented:
"
class b
{
public:
  void print(){Rect::print()}
}
"
Did you include Rect.h?
Also, you can call Rect::print only if it is a static method, otherwise you must do
class b : public Rect
(assuming the method is virtual, otherwise, you'd get it to work but that would be unmaintainable).
Commented:
By default a nested calss doesn't have an access to private members of the outer class. However, you can declare an outer class as a friend of the inner class for example:

class a
{
private
 void foo();
 
 class b
 {
 friend class a; // this will do the trick
 //... members, whatsoever
 };
};

Sincerely,
Kender

P.S. one class can have several friends.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.