Sign in to follow this  

Dual constructors/destructors?

This topic is 3635 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

//The ObjectData Struct
struct ObjectData{
        std::string Filename;
	LPD3DXMESH Mesh;

	Object(char* a);
	~ObjectData();
};

//The ObjectData Constructor
ObjectData::ObjectData(char* a) {
	Filename = a;
}
//The ObjectData Destructor
ObjectData::~ObjectData() {
	Mesh->Release();
}

//The Object Struct
struct Object{
	ObjectData Data;
	/*
	More stuff here
	*/
};


I have made two struct types, Object and ObjectData. ObjectData is a member of Object. How do I use ObjectData's constructor and destructor?

Share this post


Link to post
Share on other sites
For non pointer/reference members, the destructor will be called automatically after the destructor of the enclosing type finishes (even if you don't write such a destructor).

To call the constructor, use an initialiser list:


struct ObjectData{
std::string Filename;
LPD3DXMESH Mesh;

// note, don't use char pointers
ObjectData(const std::string &filename);
~ObjectData();
};

// use meaningful variable names. 'a' is not such a name
ObjectData::ObjectData(const std::string &Filename)
// use a colon after the parameter list to start an initialiser list
:
// list the members you wish to call
// in order they appear in the object definition
// you can also call superclass constructors in this way
Filename(Filename),
Mesh(0)
{
} // it is common for constructor bodies to be empty when using initialiser lists

ObjectData::~ObjectData()
{
// should this be wrapper in
// if(Mesh) {
Mesh->Release();
// }
}

struct Object{
ObjectData Data;

Object( const std::string &filename )
:
Data(filename)
{
}
};




Share this post


Link to post
Share on other sites
Quote:
Original post by rip-off
For non pointer/reference members, the destructor will be called automatically after the destructor of the enclosing type finishes (even if you don't write such a destructor).

To call the constructor, use an initialiser list:

*** Source Snippet Removed ***


Wow thanks! :D

Share this post


Link to post
Share on other sites

This topic is 3635 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