Dave's Brain

Browse - Programming Tips - What should a typical C++ class look like?

Date: 2005Jun1
Language: C++


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; } };

Add a comment

Sign in to add a comment
Copyright © 2008-2017, 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.