• Advertisement
Sign in to follow this  

C++ Class Question

This topic is 4179 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 have been working on a C++ project, and I am trying to get the hang of using classes. How might I go about creating an object of one class within another, if that is possible? As a basic example of what I want to do: class A { private: //int something //float somethingelse //so on.... public: //Constructor, methods and so on }; class B { private: A aClass;//Create an object from class A to use in class B public: //Constructor, methods and so on }; I just need some way to create class objects within other classes. Any help would be much appreciated:)

Share this post


Link to post
Share on other sites
Advertisement
Quote:

I just need some way to create class objects within other classes


There is a way! The way you just described! [smile]

'A' is just a type. Just like you can have a member 'int anInt' you can have a member 'A aClass' just like you posted. The only catch is if the constructor of A requires parameters. Then you must initialize aClass inside B's constructor initializer list. This would look like this:


class A
{
public:
A(int x){}
};

class B
{
private:
A aClass;
public:
B():aClass(42){}
}




Inheritance is something different. It denotes an is-a relationship(for example, an AppleTree is a Tree), whereas what you describe is a has-a relationship(for example, an AppleTree contains objects of class Apple).

Share this post


Link to post
Share on other sites
Thanks:) My class did require parameters for its constructor. This seems to be what I was looking for. Thanks again.


Share this post


Link to post
Share on other sites
[source lan="c"]
class A
{
private:
//int something
//float somethingelse
//so on....

public:
//Constructor, methods and so on
A(int a, float f);

};

class B
{
private:
A aClass;//Create an object from class A to use in class B

public:
//Constructor, methods and so on

// With an initialiser list you can
// See :)
B() : A(10, 5.5f) {}

};

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement