Professional Documents
Culture Documents
1 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
2 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
69
70 // C++ does not support Array of References
71 // Point & pts[2] = {p1, p2}; // error: declaration of 'pts' as array of references
72 }
Classes: A class is a abstract or user-defined data type, contrast to built-in fundamental types such as int or double . A class is represented as a three-
compartment box: name, date members (or variables or a�ributes) and member func�ons (or methods, or opera�ons). The data member and member
func�ons are collec�vely called class members. The syntax of defining a class consists of two sec�ons: class declara�on and class implementa�on. Class
declara�on is further divided into two sec�ons: private and public sec�ons. Class implementa�on contains member func�on defini�ons.
Objects (or instances): An object (or instance) is a concrete realiza�on of a class. For example, Point is a class, we can create instances (objects) p1, p2,
p3, belonging to the class Point. You can invoke the constructor implicitly or explicitly as follows:
There are a few ways to use a class to create instances, as shown in the above test driver program:
1. Construct instances (or objects) via constructors, either implicitly or explicitly.
2. Declare object pointers, and construct the objects dynamically via new operator.
3. Declare object references, and ini�alized to an exis�ng object, or received as func�on reference argument.
4. Array of objects, or Array of object pointers (dynamically allocated via new[] operator).
Data Members: Similar to normal variables, but having so-called class scope such as private or public. The syntax of declaring a data member is the
same as declaring a normal variable:
type variableName;
A data member cannot be ini�alized (except const sta�c data variables) in C++03.
Member Functions: Again, similar to normal func�ons, but having class scope. The syntax of declaring a member func�on is the same as normal func�on:
returnType functionName(parameter-type-list);
Constant Member Functions: A const member func�on, iden�fied by a const keyword at the end of the member func�on's header, cannot modifies
any data member of this object. For example,
Implementing Member Functions: Member func�ons are usually implemented outside class declara�on. You need to use the scope resolu�on operator
:: to iden�fy functionName as a member of a par�cular ClassName.
returnType ClassName::functionName(parameter-list) {
function-body;
}
public vs. private Access Specifier: private members are accessible by the member func�ons of this class only. public members are
accessible everywhere. For example, if p1 is an instance of Point, p1.getX() is allowed outside the class defini�on (such as main()) as getX() is
public. However, p1.x is not allowed in main(), as x is declared private.
Constructor: A constructor is a special func�on having the "same name" as the classname, with no return-type. As the name implied, constructor is called
each �me when an instance is declared (or constructed). Constructor is used for ini�alizing the data members of the instances created. The syntax is:
3 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
Member Initializer List : used to ini�alize data members in the constructor. For example,
The member ini�alizer list is placed a�er the func�on parameter list, separated by a colon. For fundamental-type data members (e.g., int, double), x(x) is
the same as this->x = x. For object data members, the copy constructor will be invoked for each of the object. The func�on body will be executed a�er the
member ini�alizer list, which is empty in this case.
Alterna�vely, you could ini�alize the data members inside the constructor's body:
Point::Point(int x, int y) {
this->x = x;
this->y = y;
}
where this->x refers to the data member x; and x refer to the func�on parameter x.
Default Constructor: The default constructor refers to the constructor that takes no parameter - either it has no parameter or all parameters have their
default value (e.g., the above Point's constructor). If no constructor is defined in the class, the compiler inserts a default constructor that takes no argument
and does nothing (i.e., ClassName::ClassName() {}). However, if you define one (or more) constructors, compiler will not insert the default constructor.
You need to define your default constructor, if desired.
Function Overloading: A func�on (including constructor) can have many versions, differen�ated by its parameter list (number, types and orders of
parameters). Caller can choose to invoke a par�cular version by matching the parameter list.
Function Default Argument: In C++, default values can be assigned to trailing func�on's parameters. If the caller does not supply these arguments,
compiler would insert the default value accordingly. For example,
Notes:
The default value can only be assigned to the trailing arguments.
The default value shall be specified in the class declara�on. I shall NOT be specified in the func�on implementa�on.
Default argument is applicable to all func�ons, including constructor func�on.
Constructing Instances: As men�oned, instances (or objects) are concrete realiza�ons of a class. A constructor would be invoked when declaring an
instance to ini�alize the instance. The syntax to declare an instance is:
Public Getters and Setters for Private Variables: Member variables are usually declared private to prevent direct access (called data hiding).
Instead, public ge�er and se�er are defined to retrieve (get) and modify (set) the private member variable. The conven�on is as follows:
class ClassName {
private:
type xxx; // private variable
public:
type getXxx() const; // public getter
void setXxx(type); // public setter (use const type if type is a class)
}
// Getter Implementation
type ClassName::getXxx() const { return xxx; }
// Setter Implementation
void ClassName::setXxx(type x) { xxx = x; }
// OR
4 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
Implementing Member Functions in Class Declaration: You can include the func�on's implementa�on inside the class declara�on, as follows:
Func�ons that implemented inside the class declara�on are automa�cally treated as inline func�ons. That is, they will be expanded in place by the compiler (if
the compiler chooses to do so), instead of performing a more expensive func�on call.
Dot (.) Member Selection Operator: Dot operator (.) is used to access public class members, in the form of instanceName.memberName, e.g.,
point1.getX(), point2.print().
Arrow (->) Member Selection Operator: Arrow operator (->) is used with object pointer. Suppose *pObj is a pointer to an object, instead of using
(*pObj).member to select a member, it is more convenient to use the arrow nota�on, in the form of pObj->member.
Memberwise Assignment: The assignment operator (=) can be used to assign one object into another object (of the same class), in memberwise manner.
For example,
(Note: The compiler automa�cally generates an implicit assignment operator operator=(), which performs memberwise copying.)
Passing Objects into Function: Objects are passed by value into func�on. A copy is created (via memberwise assignment) and passed into the func�on.
The caller's copy cannot be modified inside the func�on.
Object Pointer and Dynamic Allocation: To allocate an instance of a class dynamically, define an object pointer and use new operator to allocate the
storage. The new operator return a pointer poin�ng to the storage allocated. You could use arrow operator -> to access the members with object pointer in the
form of pObj->member (same as (*pObj).member). You need to use the delete operator to free the allocated storage.
Similarly, you can use new[] and delete[] to dynamically allocate array of objects.
5 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
27 }
Object Reference: You can create an object reference to an exis�ng object. A reference is similar to a pointer, but it is a name constant that is referenced
and de-reference implicitly by the compiler.
Object references are useful in passing object into func�on by reference (by default, objects are passed into func�on by value).
Destructor: Similar to constructor, a destructor has the same name as the classname, but preceded with a �lde (~). The destructor is called automa�cally
when the instance expires. It has no-argument, no return type. There can be only one destructor in a class. If there is no destructor defined, the compiler
supplies a destructor that does nothing.
Destructor shall do the clean up, in par�cular, the dynamically allocated memory. If the constructor uses new to dynamically allocate storage, the destructor
should delete them.
2. Inheritance
2.1 Terminology
Superclass (Base Class) & Subclass (Derived Class): In OOP, we could organize classes in hierarchy to avoid redundancy. We can extend a subclass
(or derived class) from a superclass (or base class). The subclass inherits the members of the superclass, known as inheritance.
The subclass inherits all the members of the superclass. The subclass shall define its own constructor(s). It may define addi�onal members (data or func�ons).
Access Specifier: C++ supports three access specifier: private, public and protected. A private member is accessible within the class by
member func�ons and by friends of that class. A public member is accessible by all. A protected member can be accessed by itself and its friend, as well
as its subclasses and their friends.
To access a superclass's member explicitly, you could use the scope resolu�on operator in the form of superclassName::memberName.
Inheritance Access Specifier: It specifies the type of inheritance: public, private or protected. The most commonly used is public-
inheritance. In this case, the inherited members in the subclass have the same visibility as the superclass. There is no further restric�on. In other words,
public members in the superclass becomes public members in the derived class; protected members in the base class become protected member
in the derived class. In this case, every subclass object is also a superclass object (known as is-a rela�onship), and can be subs�tuted for a superclass reference.
private- and protected-inheritance, which are rarely used, may further restrict the access of the inherited members (equal or lower than the access in
superclass). In protected-inheritance, public and protected members in the base class become protected members in the derived class. In
private-inheritance, public and protected members in the base class become private member in the derived class. Take note the private
members in the superclass cannot be directly accessed in the subclass; while protected members can be directly accessed.
6 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
Notes:
When the subclass construct its instance, it must first construct a superclass object, which it inherited.
The subclass does not have direct access to superclass' private members x, and y. To ini�alize these inherited members, the subclass constructor
invokes the superclass constructor, which is public, in the member ini�alizer list.
You need to use the member ini�alizer list (: Point(x, y)) to invoke the superclass Point's constructor to ini�alize the superclass, before ini�alizing
the subclass. Object data member can only be ini�alized via member ini�alizer list.
If you did not explicitly invoke the superclass' constructor, the compile implicitly invoke the superclass' default constructor to construct a superclass object.
To use the superclass members, use scope resolu�on operator in the form of SuperclassName::memberName. For example, Point::print(),
7 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
Point::getX().
// Compile and link TestMovablePoint.cpp with object files into executable file
> g++ -o TestMovablePoint.exe TestMovablePoint.cpp MovablePoint.o Point.o
void MovablePoint::move() {
x += xSpeed; // error: 'int Point::x' is private
// Point::setX(Point::getX() + xSpeed);
Point::setY(Point::getY() + ySpeed);
}
However, if we make x protected instead of private, the subclass can access x directly.
// Superclass Point
class Point {
protected:
int x, y;
......
};
// Subclass MovablePoint
class MovablePoint : public Point {
......
}
void MovablePoint::move() {
x += xSpeed;
y += ySpeed;
}
3. Polymorphism
8 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
Polymorphism works on object pointers and references using so-called dynamic binding at run-�me. It does not work on regular objects, which uses sta�c
binding during the compile-�me.
We typically allocate object dynamically via the new operator and manipulate the return pointer in polymorphism. Recall that we can dynamically allocate
objects for the Point and MovablePoint classes as follows:
3.1 Substitution
A subclass instance inherits all the proper�es of the superclass, in the case of public-inheritance. It can do whatever a superclass instance can do. This is
known as a "is-a" rela�onship. Hence, you can subs�tute a subclass instance to a superclass reference.
Example
Using the above example of superclass Point and subclass MovablePoint,
Once subs�tuted, it can invoke all the func�ons defined in the superclass, but CANNOT invoke func�ons defined in the subclass. This is because the reference is
a superclass reference, which is not aware of subclass members.
3.2 Polymorphism
1. A subclass instance can be subs�tuted for a superclass reference.
2. Once subs�tuted, only the superclass' func�ons can be called, no the subclass'.
3. If the subclass overrides a superclass func�on. We wish to run the overridden version in the subclass, instead of the superclass' version (as in the previous
example).
Virtual Functions: To implement polymorphism, we need to use the keyword virtual for func�ons that are meant to be polymorphic. In this case, if a
superclass pointer is aiming at a subclass objects, and invoke a virtual func�on that is overridden by the subclass, the subclass version will be invoked,
instead of the superclass version. For example,
// Point.h
class Point {
......
virtual void print() const;
}
9 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
3 #include <iostream>
4 #include "MovablePoint.h" // included "Point.h"
5 using namespace std;
6
7 int main() {
8 // Substitute a subclass instance to a superclass reference
9
10 // Using Object Pointer
11 Point * ptrP1 = new MovablePoint(11, 12, 13, 14); // upcast
12 ptrP1->print(); // MovablePoint @ (11,12) Speed=(13,14)
13 // - Run subclass version!!
14 cout << endl;
15 delete ptrP1;
16
17 // Using Object Reference
18 MovablePoint mp2(21, 22, 23, 24);
19 Point & p2 = mp2; // upcast
20 p2.print(); // MovablePoint @ (21,22) Speed=(23,24)
21 // - Run subclass version!!
22 cout << endl;
23
24 // Using object with explicit constructor
25 Point p3 = MovablePoint(31, 32, 33, 34); // upcast
26 p3.print(); // Point @ (31,32) - Run superclass version!!
27 cout << endl;
28 }
The keyword virtual determines which method is used if the method is invoked by a pointer (or reference). Without virtual, the program chooses the
method based on the pointer type; with virtual, the program chooses the method based on the type of the object pointed-to.
Take note that virtual func�ons work on object pointers (and references), but not on regular objects.
If the subclass override a method inherited from its superclass, the usual prac�ce is to declare the superclass method as virtual. In this case, the program
will choose the method based on the type of the object, instead of the type of pointer.
For non-virtual func�on, the compiler selects the func�on that will be invoked at compiled-�me (known as sta�c binding). For virtual func�ons, the selec�on is
delayed un�l the run�me. The func�on selected depends on the actual type that invokes the func�on (known as dynamic binding or late binding).
Using Polymorphism:
1. Create instances of concrete subclass.
2. Declare superclass (possibly abstract) pointers (or references).
3. Aim the superclass pointers to the subclass instances.
4. Invoke virtual func�on, with implementa�on provided by subclass.
int i = 8;
double * ptr1 = &i;
// error: cannot convert 'int*' to 'double*' in initializatin
double & d = i;
// error: invalid initialization of reference of type 'double&' from expression of type 'int'
However, a pointer or reference of superclass can hold a subclass object without explicit type cast:
MovablePoint mp(.....);
Point * ptrP1 = ∓ // Okay - Implicit upcast
Point & p2 = mp; // Okay - Implicit upcast
Conver�ng a subclass to superclass reference or pointer is called upcas�ng. (Because in UML diagram, we o�en draw the superclass on top of the subclass, with
an arrow poin�ng up from the subclass to the superclass.) Upcas�ng is always allow for public-inheritance without the need for an explicit type cast, because
10 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
public-inheritance exhibits is-a rela�onship. A subclass object is a superclass object, because it inherits all the a�ributes and opera�ons from the superclass,
and can do whatever the superclass object can do.
The reverse opera�on, conver�ng a superclass reference or pointer to subclass, is called downcas�ng. Downcas�ng requires explicit type cast.
Operator dynamic_cast
C++ provides a new cas�ng operator called dynamic_cast<type>(value), which returns a null pointer if the type cast fails. For example,
Operator typeid
The operator typeid returns a reference to an object of class type_info (in header <typeinfo>, which contains informa�on about the type of its operands.
You can use type_info's member func�on name() to get the type name. For example,
Program Notes:
The number in front of the name gives the length of the string.
A pure virtual func�on usually has no implementa�on body, because the class does not know how to implement the body. A class containing one or more pure
virtual func�on is called an abstract class. You cannot create instances from an abstract class, because its defini�on may be incomplete.
Abstract class is meant to be a superclass. To use an abstract class, you need to derive a subclass, override and provide implementa�on to all the pure virtual
func�ons. You can then create instances from the concrete subclass.
C++ allows implementa�on for pure virtual func�on. In this case, the =0 simply make the class abstract. As the result, you cannot create instances.
11 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
Shape.h
1 /* Header for Shape class (Shape.h) */
2 #ifndef SHAPE_H
3 #define SHAPE_H
4
5 #include <string>
6 using namespace std;
7
8 class Shape {
9 private:
10 string color; // Private data member
11
12 public:
13 Shape(const string & color = "red"); // Constructor
14 string getColor() const; // Getter
15 void setColor(const string & color); // Setter
16 // Virtual function, run subclass version if overridden
17 virtual void print() const;
18 // Pure virtual, to be implemented by subclass
19 // You cannot create instance of Shape
20 virtual double getArea() const = 0;
21 };
22
23 #endif
Shape.cpp
1 /* Implementation for Shape class (Shape.cpp) */
2 #include "Shape.h"
3 #include <iostream>
4
5 // Constructor
6 Shape::Shape(const string & color) {
7 this->color = color;
8 }
9
10 // Getter
11 string Shape::getColor() const {
12 return color;
13 }
14
15 // Setter
16 void Shape::setColor(const string & color) {
17 this->color = color;
18 }
19
20 void Shape::print() const {
21 std::cout << "Shape of color=" << color;
22 }
Circle.h
12 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
Circle.cpp
1 /* Implementation for Circle (Circle.cpp) */
2 #include "Circle.h"
3 #include <iostream>
4 #define PI 3.14159265
5
6 // Constructor
7 Circle::Circle(int radius, const string & color)
8 : Shape(color), radius(radius) { }
9
10 // Getters
11 int Circle::getRadius() const {
12 return radius;
13 }
14
15 // Setters
16 void Circle::setRadius(int radius) {
17 this->radius = radius;
18 }
19
20 void Circle::print() const {
21 std::cout << "Circle radius=" << radius << ", subclass of ";
22 Shape::print();
23 }
24
25 // Implement virtual function inherited for superclass Shape
26 double Circle::getArea() const {
27 return radius * radius * PI;
28 }
Rectangle.h
1 /* Header for Rectangle class (Rectangle.h) */
2 #ifndef RECTANGLE_H
3 #define RECTANGLE_H
4
5 #include "Shape.h"
6
7 // The class Rectangle is a subclass of Shape
8 class Rectangle : public Shape {
9 private:
10 int length;
11 int width;
12
13 public:
14 Rectangle(int length = 1, int width = 1, const string & color = "red");
15 int getLength() const;
16 void setLength(int length);
17 int getWidth() const;
18 void setWidth(int width);
19 void print() const; // Override the virtual function
20 double getArea() const; // to implement virtual function
21 };
22
13 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
23 #endif
Rectangle.cpp
1 /* Implementation for Rectangle (Rectangle.cpp) */
2 #include "Rectangle.h"
3 #include <iostream>
4
5 // Constructor
6 Rectangle::Rectangle(int length, int width, const string & color)
7 : Shape(color), length(length), width(width) { }
8
9 // Getters
10 int Rectangle::getLength() const {
11 return length;
12 }
13 int Rectangle::getWidth() const {
14 return width;
15 }
16
17 // Setters
18 void Rectangle::setLength(int length) {
19 this->length = length;
20 }
21 void Rectangle::setWidth(int width) {
22 this->width = width;
23 }
24
25 void Rectangle::print() const {
26 std::cout << "Rectangle length=" << length << " width=" << width << ", subclass of ";
27 Shape::print();
28 }
29
30 // Implement virtual function inherited from superclass Shape
31 double Rectangle::getArea() const {
32 return length * width;
33 }
14 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
[TODO] Explana�on
4. More On OOP
Constant Member Functions: We declare a member func�on constant by placing the keyword const a�er the parameter list. A const member
func�on cannot modify any member variable. For example,
A constant member func�on cannot modify data members too. For example,
The constructor and destructor cannot be made const, as they need to ini�alize data members. However, a const object can invoke non-const constructor.
The const property begins a�er construc�on.
15 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
A non-const string object will run the non-const version, which returns a non-const char reference. The return reference can be used as the lvalue to
modify the char, e.g., str.at(1) = 'x'. On the other hand, a const string object will invoke the const member func�on, which returns a const
char reference. A const reference cannot be used as lvalue. For example,
A member ini�alizer list is placed a�er the parameter list, in the form of : data-member-name(value), .... Using this->y = y triggers a compila�on
error due to the assignment into const data member y.
For object data member, you can use the member ini�alizer list to trigger its constructor. member ini�alizer list is also use to invoke superclass constructor from
the subclass constructor.
16 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
friend Functions
A "friend" func�on of a class, marked by the keyword friend, is a func�on defined outside the class, yet its argument of that class has unrestricted access to
all the class members (private, protected and public data members and member func�ons).
For example,
1 /*
2 * Test Friend Function (TestFriend.cpp)
3 */
4 #include <iostream>
5 using namespace std;
6
7 class Point {
8 // A friend function defined outside this class, but its argument of
9 // this class can access all class members (including private members).
10 friend void set(Point & point, int x, int y); // prototype
11 private:
12 int x, y;
13 public:
14 Point(int x = 0, int y = 0) : x(x), y(y) { }
15 void print() const { cout << "(" << x << "," << y << ")" << endl; }
16 };
17
18 // Friend function is defined outside the class
19 void set(Point & point, int x, int y) {
20 point.x = x; // can access private data x and y
21 point.y = y;
22 }
23
24 int main() {
25 Point p1;
26 p1.print(); // (0, 0)
27 set(p1, 5, 6);
28 p1.print(); // (5, 6)
29 }
Notes:
A friend func�on is a regular func�on, NOT a member func�on of the class. Hence it is invoked without the dot operator in the form of set(p1, 5, 6),
instead of p1.set(5, 6) for a member func�on.
The above example is meant for illustra�on. This opera�on is be�er served by a member func�on void set(int x, int y), instead of friend
func�on.
The friend func�on prototype is provided inside the class declara�on. You do not need to provide another prototype outside the class declara�on, but
merely provide its implementa�on.
Friend func�ons can enhance the performance by directly accessing the private data members, elimina�ng the overhead of going thru the public member
func�ons.
Friend func�ons are neither public nor private, and it can be declared anywhere inside the class. As friends are part of the extended interface of the class,
you may group them together with the public func�ons.
Friend func�ons will not be inherited by the subclass. Friends can't be virtual, as friends are not class member.
friend Class
To declare all member func�ons of a class (says Class1) friend func�ons of another class (says Class2), declared "friend class Class1;" in
Class2.
Friends are not symmetric. That is, if Class1 is a friend of Class2, it does not imply that Class2 is a friend of Class1. Friends are also not transi�ve. That
is, if Class1 is a friend of Class2, and Class2 is a friend of Class3, it does not imply that Class1 is a friend of Class3.
Use friend with care. Incorrect use of friends may corrupt the concept of informa�on hiding and encapsula�on.
A static func�on can only access static variables, and cannot access non-static variables. A sta�c variable/func�on can be referenced without any
instan�a�on (i.e., no instance is created).
Example (static Class Member) : This example uses a static data member to keep track of the number of instances created.
Point.h
17 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
Point.cpp
1 /* Implementation for Point class (Point.cpp) */
2 #include <iostream>
3 #include "Point.h"
4 using namespace std;
5
6 // Initialize the static data member (outside the class declaration)
7 int Point::count = 0;
8
9 // A static function can access static data member
10 int Point::getCount() {
11 return count;
12 }
13
14 // Constructor
15 Point::Point(int x, int y) : x(x), y(y) {
16 ++count; // one more instance created
17 }
18
19 // A non-static member function can also access static data member (of the class)
20 void Point::print() {
21 cout << "Point number " << count << " @ (" << x << "," << y << ")" << endl;
22 }
You cannot ini�alize the static variable in the class declara�on. This is because class declara�on merely describe the memory alloca�on but does not actually
allocate the memory. Instead, it is ini�alized outside the declara�on as shown above. The ini�aliza�on is kept in the implementa�on file, instead of header, so as
not the repeat the same step when header file in included.
TestPoint.cpp
1 /* Test Driver Program for Point class (TestPoint.cpp) */
2 #include <iostream>
3 #include "Point.h"
4 using namespace std;
5
6 int main() {
7 Point p1;
8 p1.print();
9 cout << Point::getCount() << " instances created" << endl;
10 Point p2(1, 2);
11 p2.print();
12 cout << Point::getCount() << " instances created" << endl;
13 Point p3(3);
14 p3.print();
15 cout << Point::getCount() << " instances created" << endl;
16 }
Program Notes:
A static data member retains this value throughout its life span.
To reference a static class member, you need to use ClassName::staticMemberName. You CANNOT invoke static member func�on from an
instance, such as p1.getCount().
A static data member can be accessed by static and non-static member func�ons. However, a static func�on member can only access
static data members, and CANNOT access non-static data members. For example,
18 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
5. More On Inheritance
[TODO]
[TODO]
Default Constructor
If you did not define any constructor in a class, C++ provide a default constructor that takes no argument and does nothing. For example, if you did not define
any constructor in Point class, the following default constructor will be generated:
Point::Point() {}
The default constructor does not ini�alize the data members. For example,
1 #include <iostream>
2 using namespace std;
3
4 class Point {
5 private:
6 int x, y;
7 public:
8 void print() const { cout << "(" << x << "," << y << ")" << endl; }
9 };
10
11 int main() {
12 Point p1; // Invoke implicitly-generated default constructor
13 // Value of x and y uninitialized
14 p1.print(); // (???,???)
15 }
If you have define a constructor of with any parameter-list. C++ will not generate the default constructor. In this case, if you use default constructor without
defining one, you will get a compila�on error For example,
1 #include <iostream>
2 using namespace std;
3
4 class Point {
5 private:
6 int x, y;
7 public:
8 Point(int x, int y) : x(x), y(y) { }
9 void print() const { cout << "(" << x << "," << y << ")" << endl; }
10 };
11
12 int main() {
13 Point p1;
14 // error: no matching function for call to 'Point::Point()'
15 }
A constructor with arguments can be treated as a default constructor if all arguments have a default value. For example,
19 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
Copy Constructor
A copy constructor is used to construct a new object by copying the given object. It take a const reference of an object of the same class, as follows:
Point p1 = p2;
Point p1 = (Point)p2;
// Depending on compiler implementation, they may invoke the copy
// constructor to create a temporary object, and then copy over
// via memberwise assignment
In addi�on, when an object is passed by value into a func�on, and when a func�on returns an object by value, a compiler also uses the copy constructor to
generate a temporary object and then copy over via memberwise assignment. [Hence, it is more efficient to pass an object by reference into func�on, which
avoids the overhead of copying.]
The default copy constructor performs a memberwise copy of all the non-static data members. Each data member is copied by value. If the data member is
an object, the copy constructor of that object is used to do the copy. Sta�c members are not copy as they belong to the class (one copy shared by all instances).
However, if the data member is a pointer, the value of the pointer is copied - no dynamic memory alloca�on is performed to duplicate the contents pointed to
by the pointer. This is called shadow copying.
Assignment Operator
C++ allows object assignment via the assignment operator (=). It does so by automa�cally overloading the assignment operator, as follows:
The overloaded assignment operator takes an object reference and return an object reference.
Like the copy constructor, the implicit assignment operator performs memberwise copy. For object data members, the assignment operator of that class will be
used for copying. Sta�c members are not copied. Again, for pointers, the value of pointer is copied, but no dynamic alloca�on is performed to duplicate the
contents of the pointer (shadow copying).
If you use new (or new[]) to dynamically allocate memory in the constructor to object data member pointers, for example,
class ClassName {
private:
T * pObj; // object data member pointer
public:
// Constructors
ClassName(...) {
pObj = new T(...); // or new[]
....
}
// Destructor
~ClassName() {
delete pObj; // OR delete[]
}
// Copy constructor
ClassName & ClassName(const ClassName &);
You should use delete (or delete[]) in the destructor to free the dynamic memory allocated.
If you have more than one constructors, all constructors should be compa�ble with the destructor, including the default constructor. You may need to
provide you own default constructor, instead of using the implicitly generated one.
You should define a copy constructor that ini�alizes the object by deep copying the given object. The default copy constructor implicitly generated by the
compiler does shadow copying, which does not copy the contents of the pointers.
You should also define an assignment operator that deep copies one object into another.
20 of 21 22/03/2020, 19:45
Object-oriented Programming (OOP) in C++ https://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp6_Inheritan...
T * pObj;
pObj = &obj;
// OR
pObj = new T(...);
Use member-of (->) operator to refer to its class members, e.g. obj->memberName.
Use dereferencing (*) operator to get its content, e.g., *obj.
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@ntu.edu.sg) | HOME
21 of 21 22/03/2020, 19:45