160 likes | 284 Vues
This guide covers essential concepts in C++ class basics, including member data and functions, accessibility control with public, private, and friend access specifiers, and practical examples such as the implementation of the Circle class. It delves into constructors, destructors, and copy constructors, emphasizing their importance in resource management and memory safety. It also discusses assignment operators, self-assignment issues, and provides debugging tips for Visual Studio to ensure efficient code development and maintenance.
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