Dave's Brain

Browse - programming tips - class skeleton

Date: 2005Jun1

Q.  What should a typical C++ class look like?

A.

All but the most trivial classes should have a copy constructor and
an assignment operator.  Since they do basically the same thing
I typically implement them using a method called Set().
I make a member called Init() which is used by all constructors.
So a class skeleton looks like this:

class MyClass
{
	int	a;
	float	b;

public:
	void Init() // Zero everything
	{
		// Tempting to use ZeroMemory() here but don't
		a = 0;
		b = 0.0;
	}

	void Set(const MyClass &myclass) // Update all member values
	{
		// Tempting to use memcpy() here but don't
		a = myclass.a;
		b = myclass.b;
	}

	MyClass() // Default constructor
	{
		Init();
	}

	MyClass(const MyClass &c) // Copy constructor
	{
		Init(); // All constructor, even this one, call Init() first
		Set(c);
	}

	const MyClass &operator=(const MyClass &c) // Assignment operator
	{
		Set(c);
		return *this;
	}
};
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2010, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.