The world of C++, part 1

Defining and using a class


// A.h
#ifndef A_HEADER
#define A_HEADER
class A {
  // Exposed member functions or Methods
  void foo1(); // Declaration
  // Inlined function: foo2
  void foo2() {
  // Private member functions
  void foo3();
  // Data member(s)
  int data;


#include “A.h”
void A::foo2() { … }
void A::foo3() { … }


Static allocation of object
  A a;  // Default constructor invoked
  a.foo3(); // Error: Private member function
} // Destructor for a invoked
Dynamic allocation of object
A* a = new A(); // Default constructor invoked
// Use a
delete a; // Destructor invoked
A* a = new A[n]; // Calls the default constructor n times
delete [] a;

4 default methods of a class

class A{
  // No member functions defined
  int mInt;           // Data member of type int
  int* mPointerToInt; // Data member of type pointer to int
  B mb;                // Data member of type class B

This is equivalent to the following:

class A {
  // Default constructor (can be overwritten or overloaded)
  A() : mb() {
    // mb is initialized through its constructor
    // No initialization for data member of type int
    // No initialization for data member of type int*
  // Default destructor (can be overwritten)
  ~A() {
  // Default copy constructor
  A(const A& other) : mb(other.mb) {
    mInt = other.mInt;
    mPointerToInt = other.mPointerToInt;
  // Default assignment operator
  A& operator=(const A& other) {
    mInt = other.mInt;
    mPointerToInt = other.mPointerToInt;
    return *this;

Need for overwriting the 4 default methods

Data member type Need to overwrite constructor Need to overwrite destructor Need to overwrite copy constructor Need to overwrite assignment operator
Non-pointer built-in (int, float, double, char, bool) Yes (for initialization) No No No
Pointer Yes (for allocation) Yes (for deallocation) Yes (for deep copy) Yes (for deep copy)
Class No No No No


Naming values

const float g = 9.8;
g = … // Error: Illegal to modify

const -> property of the path, not of the variable data type


A a;
a = …; // Fine
void foo(const A& b) {
  b = … // Error

Const Member function -> Member variables cannot be modified by this function

class A {
  void foo() const; // equivalent to void foo(A* const this);

Since const applies to the “this” pointer (which is a pointer to the self-object), member variables cannot be modified.

Choosing function interface

Speed?(copy constructor is not invoked) Is it safe?(Callee cannot modify the caller’s actual parameter) Can it be NULL?(to indicate the absence of a value)
void A(      B  b) Slow Yes No
void A(      B* b) Fast No Yes
void A(const B* b) Fast Yes Yes
void A(      B& b) Fast No No
void A(const B& b) Fast Yes No