Sign in to follow this  

C++ Class Question

This topic is 4104 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
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
[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

This topic is 4104 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this