Archived

This topic is now archived and is closed to further replies.

A Class within another Class

This topic is 6035 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I was just wondering if you could define a class within the definition of another class. If it is possibly can someone show some example code. Thanks.

Share this post


Link to post
Share on other sites
Sure you can (not a really useful example, though):

  
#include <iostream>

using namespace std;

class A
{
public:
class B
{
public:
void foo() const { cout << "A::B::foo()\n"; }
};

void foo() const { cout << "A::foo()\n"; }
void bar() const { B b; b.foo(); }
};

int main()
{
A::B b;
A a;

a.foo();
a.bar();
b.foo();
}


This will print

A::foo()
A::B::foo()
A::B::foo()

Of course, the usual access rules (public, private, protected) also hold for the inner class (B in this case).

HTH

Share this post


Link to post
Share on other sites
I''m not sure I understand the question. If the question is "Can you use classes within classes, as data members, etc?" the answer is certainly, and let us know and we''ll give you details regarding how. If the question is "Can I define more than one class in a header file?" then the answer is yes, simply add another class block and make sure you put the right class name to the functions. If you''re curious about deriving classes from other classes to use the functionality of one class in another class with more functionality, we can give you some resources on that as well.

-fel

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Sure

class Wheel {
public:
//whatever one needs to make a wheel.
private:

};

class Car {
public:
private:
Wheel wheels[4];
};

Something like that. When making classes, just ask yourself "is
this a has-a relationship or an is-a relationship?" For example,
a car has-a wheel (actually 4 of them, usually) and a Mustang
is-a car... So Mustang would be inherited from Car while Car
possesses 4 Wheels.

Get it?

Share this post


Link to post
Share on other sites
My class looks like this:
class CMap
{
public:
int XMax;
int YMax;
int TileWidth;
int TileHeight;

class CCamera
{
public:
int X;
int Y;
void Initialize(void)
{
X = 0;
Y = 0;
}
};
};

I want to create a variable in a .h file using extern then I declare the variable in a .cpp
I keep getting error that say the CMap is undefined.

Share this post


Link to post
Share on other sites
Out of curiosity, what is the reasoning behind putting class CCamera in the middle of class CMap?

Also, why use extern rather than forward class reference?

Perhaps if you explained what you''re doing, we could give you an easier approach to it.

-fel

Share this post


Link to post
Share on other sites