160 likes | 274 Views
C++ class basics and Debugging. Jungseock Joo. C++ Class Basics. Member data and functions. Like struct Control over accessibility to its members. ( ie , public, private, friend, etc). Code example #1 – class Circle. Declaration (interface)
E N D
C++ class basics and Debugging JungseockJoo
C++ Class Basics • Member data and functions. • Like struct • Control over accessibility to its members. (ie, public, private, friend, etc)
Code example #1 – class Circle • Declaration (interface) • Identify its members and their forms (type, arguments, …)
Code example #1 – class Circle • Definition (implementation) • Specify the actions that the member functions must carry out.
Code example #1 – class Circle • Instantiation and usage
Constructor • Function to be called upon creation of an object. • Initializes values of the member variables. • Default implicit constructors don’t. • NOTE : Always check to initialize variables. Some compilers do it for you, but many other don’t. Then you have undetermined garbage values, painful to debug.
Destructor • Function to be called upon destroying of an object. • Releases dynamic resources allocated(memory). • Default implicit destructors don’t. • If we don’t, “Memory Leak”, painful to debug.
Copy Constructor • A constructor that copies from an existing instance of the same class given as an argument. • String new_string ( old_string ); • Creates a new instance, new_string, and initialize the values of member variables from old_string. • “strcpy” used to copy the contents, not the pointer. • Implicit copy constructors perform pointer-copy: (m_text = other.m_text), may cause a problem.
Assignment Operator = • Assign the values of an instance (rhs) to the other (lhs) • Just like “a = 5;”, you can define a customized assignment operator for your class. • String old_string ( “aaa” ); String new_string = old_string; // handled by copy constructor • String new_string2; new_string2 = old_string; // assignment operator - Again, implicit assignment operator performs pointer-copy.
Assignment Operator = • Version 1
Assignment Operator = • Version 1 • What’s wrong? • Self-assignment • string1 = string1;
Assignment Operator = • Version 2 • Add a protection against self-assignment
Assignment Operator = • Version 2 • Add a protection against self-assignment • Not exception-safe
Assignment Operator = • Version 3 • Swap-and-copy
Debugging in Visual Studio • demo