C++ Inheritance Programming Assignment

Unless I misunderstand what you want to achieve, you need an assignment operator for class , i.e. one that takes as the input:

What happened within your code (already explained in the answer of Bo Persson and comments there): in , you implemented an assignment operator that takes an instance of ; but in you assign an instance of ; the compiler saw no assignment operator for (the one that takes does not count), and so it generated one, which calls and then assignments for 's data members. If you defined the assignment as shown above, it would not happen and your operator would be called; notice that in this case assignments of and data members would not happen automatically.


A different situation is if you really wish to have an assignment from to , e.g. to use it with other derivatives of . Then the operator you defined will work, but in order to apply it to an instance of , you need to cast this instance to :

Needless to say that the operator you defined cannot easily access data members of specific to : e.g. to use you would need to "up-cast" to :

Revision on Classes and Objects

Let us revise the basics of OOP with an example of modeling 2D points with integer coordinates (x, y) in a class called , as shown in the class diagram.

Header File: Point.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #ifndef POINT_H #define POINT_H class Point { private: int x, y; public: Point(int x = 0, int y = 0); int getX() const; void setX(int x); int getY() const; void setY(int y); void setXY(int x, int y); void print() const; }; #endif
Implementation File: Point.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #include "Point.h" #include <iostream> using namespace std; Point::Point(int x, int y) : x(x), y(y) { } int Point::getX() const { return x; } int Point::getY() const { return y; } void Point::setX(int x) { this->x = x; } void Point::setY(int y) { this->y = y; } void Point::setXY(int x, int y) { this->x = x; this->y = y; } void Point::print() const { cout << "Point @ (" << x << "," << y << ")"; }
A Test Driver: TestPoint.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 #include "Point.h" #include <iostream> using namespace std; int main() { Point p1; Point p2(2, 2); p1.print(); cout << endl; p2.print(); cout << endl; Point * ptrP3, * ptrP4; ptrP3 = new Point(); ptrP4 = new Point(4, 4); ptrP3->print(); cout << endl; ptrP4->print(); cout << endl; delete ptrP3; delete ptrP4; Point & p5 = p2; p5.print(); cout << endl; Point ptsArray1[2]; ptsArray1[0].print(); cout << endl; ptsArray1[1].setXY(11, 11); (ptsArray1 + 1)->print(); cout << endl; Point ptsArray2[3] = {Point(21, 21), Point(22, 22), Point()}; ptsArray2[0].print(); cout << endl; (ptsArray2 + 2)->print(); cout << endl; Point * ptrPtsArray3 = new Point[2]; ptrPtsArray3[0].setXY(31, 31); ptrPtsArray3->print(); cout << endl; (ptrPtsArray3 + 1)->setXY(32, 32); ptrPtsArray3[1].print(); cout << endl; delete[] ptrPtsArray3; Point & pts[2] = {p1, p2}; // error: declaration of 'pts' as array of references }

Classes: A class is a abstract or user-defined data type, contrast to built-in fundamental types such as or . A class is represented as a three-compartment box: name, date members (or variables or attributes) and member functions (or methods, or operations). The data member and member functions are collectively called class members. The syntax of defining a class consists of two sections: class declaration and class implementation. Class declaration is further divided into two sections: and sections. Class implementation contains member function definitions.

class ClassName { private: private-data-membersprivate-member-functions public: public-data-memberspublic-member-functions }; member-function-definitions

Objects (or instances): An object (or instance) is a concrete realization of a class. For example, is a class, we can create instances (objects) , , , belonging to the class . You can invoke the constructor implicitly or explicitly as follows:

Point p2(1, 2); Point p3; Point p5 = Point(1, 2); Point p6 = Point();

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 operator.
  3. Declare object references, and initialized to an existing object, or received as function reference argument.
  4. Array of objects, or Array of object pointers (dynamically allocated via operator).

Data Members: Similar to normal variables, but having so-called class scope such as or . The syntax of declaring a data member is the same as declaring a normal variable:

typevariableName;

A data member cannot be initialized (except const static data variables) in C++03.

Member Functions: Again, similar to normal functions, but having class scope. The syntax of declaring a member function is the same as normal function:

returnTypefunctionName(parameter-type-list);

Constant Member Functions: A member function, identified by a keyword at the end of the member function's header, cannot modifies any data member of this object. For example,

int getX() const;

Implementing Member Functions: Member functions are usually implemented outside class declaration. You need to use the scope resolution operator to identify as a member of a particular .

returnTypeClassName::functionName(parameter-list) { function-body; }

public vs. private Access Specifier: members are accessible by the member functions of this class only. members are accessible everywhere. For example, if is an instance of , is allowed outside the class definition (such as ) as is . However, is not allowed in , as x is declared .

Constructor: A constructor is a special function having the "same name" as the classname, with no return-type. As the name implied, constructor is called each time when an instance is declared (or constructed). Constructor is used for initializing the data members of the instances created. The syntax is:

class ClassName { ClassName(parameter-list); } ClassName::ClassName(parameter-list) { function-body; }

Member Initializer List: used to initialize data members in the constructor. For example,

Point::Point(int x, int y) : x(x), y(y) { }

The member initializer list is placed after the function parameter list, separated by a colon. For fundamental-type data members (e.g., , ), is the same as . For object data members, the copy constructor will be invoked for each of the object. The function body will be executed after the member initializer list, which is empty in this case.

Alternatively, you could initialize the data members inside the constructor's body:

Point::Point(int x, int y) { this->x = x; this->y = y; }

where refers to the data member ; and refer to the function parameter .

Another alternative that avoids naming conflict, but is hard to read:

Point::Point(int x_, int y_) { x = x_; y = y_; }

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 '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., ). 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 function (including constructor) can have many versions, differentiated by its parameter list (number, types and orders of parameters). Caller can choose to invoke a particular version by matching the parameter list.

Function Default Argument: In C++, default values can be assigned to trailing function's parameters. If the caller does not supply these arguments, compiler would insert the default value accordingly. For example,

class Point { ...... Point(int = 0, int = 0); } Point::Point(int x, int y) : x(x), y(y) { } Point p1; Point p2(4); Point p3(5, 6);

Notes:

  • The default value can only be assigned to the trailing arguments.
  • The default value shall be specified in the class declaration. I shall NOT be specified in the function implementation.
  • Default argument is applicable to all functions, including constructor function.

Constructing Instances: As mentioned, instances (or objects) are concrete realizations of a class. A constructor would be invoked when declaring an instance to initialize the instance. The syntax to declare an instance is:

ClassNameinstanceName; ClassNameinstanceName(constructor-parameter-list);

Public Getters and Setters for Private Variables: Member variables are usually declared to prevent direct access (called data hiding). Instead, getter and setter are defined to retrieve (get) and modify (set) the member variable. The convention is as follows:

class ClassName { private: type xxx; public: type getXxx() const;void setXxx(type); } typeClassName::getXxx() const { return xxx; } void ClassName::setXxx(type x) { xxx = x; } void ClassName::setXxx(type xxx) { this->xxx = xxx; }

Implementing Member Functions in Class Declaration: You can include the function's implementation inside the class declaration, as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #include <iostream> using namespace std; class Point { private: int x, y; public: Point(int x = 0, int y = 0) : x(x), y(y) { } int getX() const { return x; } int getY() const { return y; } void setX(int x) { this->x = x; } void setY(int y) { this->y = y; } void setXY(int x, int y) { this->x = x; this->y = y; } void print() const { cout << "Point @ (" << x << "," << y << ")"; } };

Functions that implemented inside the class declaration are automatically treated as inline functions. That is, they will be expanded in place by the compiler (if the compiler chooses to do so), instead of performing a more expensive function call.

Dot () Member Selection Operator: Dot operator () is used to access class members, in the form of , e.g., , .

Arrow () Member Selection Operator: Arrow operator () is used with object pointer. Suppose is a pointer to an object, instead of using to select a member, it is more convenient to use the arrow notation, in the form of .

Memberwise Assignment: The assignment operator () can be used to assign one object into another object (of the same class), in memberwise manner. For example,

Point p1(4, 5); Point p2 = p1;

(Note: The compiler automatically generates an implicit assignment operator , which performs memberwise copying.)

Passing Objects into Function: Objects are passed by value into function. A copy is created (via memberwise assignment) and passed into the function. The caller's copy cannot be modified inside the function.

Pass by reference can be archived by passing an object pointer or an object reference.

Object Pointer and Dynamic Allocation: To allocate an instance of a class dynamically, define an object pointer and use operator to allocate the storage. The operator return a pointer pointing to the storage allocated. You could use arrow operator to access the members with object pointer in the form of (same as ). You need to use the operator to free the allocated storage.

Similarly, you can use and to dynamically allocate array of objects.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 #include "Point.h" #include <iostream> using namespace std; int main() { ptrP1->print(); cout << endl; Point * ptrP2 = new Point(2, 2); ptrP2->print(); cout << endl; delete ptrP1;delete ptrP2;Point * ptrPtsArray = new Point[2]; ptrPtsArray[1].setXY(31, 31); ptrPtsArray[1].print(); cout << endl; delete[] ptrPtsArray; }

Object Reference: You can create an object reference to an existing object. A reference is similar to a pointer, but it is a name constant that is referenced and de-reference implicitly by the compiler.

Point p1(1, 2); Point & p2 = p1;

Object references are useful in passing object into function by reference (by default, objects are passed into function by value).

Destructor: Similar to constructor, a destructor has the same name as the classname, but preceded with a tilde (). The destructor is called automatically 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 particular, the dynamically allocated memory. If the constructor uses to dynamically allocate storage, the destructor should them.

Inheritance

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 syntax for deriving a subclass from a superclass is as follows:

class SubclassName : inheritance-access-specifierSuperclassName { ...... };

The subclass inherits all the members of the superclass. The subclass shall define its own constructor(s). It may define additional members (data or functions).

Access Specifier: C++ supports three access specifier: , and . A member is accessible within the class by member functions and by friends of that class. A member is accessible by all. A 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 resolution operator in the form of .

Inheritance Access Specifier: It specifies the type of inheritance: , or . The most commonly used is -inheritance. In this case, the inherited members in the subclass have the same visibility as the superclass. There is no further restriction. In other words, members in the superclass becomes members in the derived class; members in the base class become member in the derived class. In this case, every subclass object is also a superclass object (known as is-a relationship), and can be substituted for a superclass reference.

- and -inheritance, which are rarely used, may further restrict the access of the inherited members (equal or lower than the access in superclass). In -inheritance, and members in the base class become members in the derived class. In -inheritance, and members in the base class become member in the derived class. Take note the members in the superclass cannot be directly accessed in the subclass; while members can be directly accessed.

Example: Superclass Point and subclass MovablePoint

[TODO] Description

Superclass Point.h, Point.cpp

No change.

Subclass Header: MovablePoint.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #ifndef MOVING_POINT_H #define MOVING_POINT_H #include "Point.h" class MovablePoint : public Point { private: int xSpeed, ySpeed; public: MovablePoint(int x, int y, int xSpeed = 0, int ySpeed = 0); int getXSpeed() const; int getYSpeed() const; void setXSpeed(int xSpeed); void setYSpeed(int ySpeed); void move(); void print() const; }; #endif
Subclass Implementation: MovablePoint.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include <iostream> #include "MovablePoint.h" using namespace std; MovablePoint::MovablePoint(int x, int y, int xSpeed, int ySpeed) : Point(x, y), xSpeed(xSpeed), ySpeed(ySpeed) { } int MovablePoint::getXSpeed() const { return xSpeed; } int MovablePoint::getYSpeed() const { return ySpeed; } void MovablePoint::setXSpeed(int xs) { xSpeed = xs; } void MovablePoint::setYSpeed(int ys) { ySpeed = ys; } void MovablePoint::print() const { cout << "Movable"; cout << " Speed=" << "(" << xSpeed << "," << ySpeed << ")"; } void MovablePoint::move() { Point::setX(Point::getX() + xSpeed); Point::setY(Point::getY() + ySpeed); }

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' members , and . To initialize these inherited members, the subclass constructor invokes the superclass constructor, which is , in the member initializer list.
  • You need to use the member initializer list () to invoke the superclass 's constructor to initialize the superclass, before initializing the subclass. Object data member can only be initialized via member initializer 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 resolution operator in the form of . For example, , .
A Test Driver: TestMovablePoint.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 #include <iostream> #include "MovablePoint.h" using namespace std; int main() { Point p1(4, 5); p1.print(); cout << endl; MovablePoint mp1(11, 22); mp1.print(); cout << endl; mp1.setXSpeed(8); mp1.move(); mp1.print(); cout << endl; MovablePoint mp2(11, 22, 33, 44); mp2.print(); cout << endl; mp2.move(); mp2.print(); cout << endl; }

To compile/link (aka build) the program:

> g++ -c Point.cpp > g++ -c MovablePoint.cpp > g++ -o TestMovablePoint.exe TestMovablePoint.cpp MovablePoint.o Point.o

Example: Point and MovablePoint with protected Data Members

Recall that a data member in the superclass is not accessible in the subclass. For example, in the function of , you cannot reference of superclass directly.

void MovablePoint::move() { x += xSpeed; Point::setY(Point::getY() + ySpeed); }

However, if we make instead of , the subclass can access directly.

class Point { protected: int x, y; ...... }; class MovablePoint : public Point { ...... } void MovablePoint::move() { x += xSpeed; y += ySpeed; }

[TODO] more examples

Polymorphism

Polymorphism works on object pointers and references using so-called dynamic binding at run-time. It does not work on regular objects, which uses static binding during the compile-time.

We typically allocate object dynamically via the operator and manipulate the return pointer in polymorphism. Recall that we can dynamically allocate objects for the and classes as follows:

Point * p1 = new Point(1, 2); p1->print(); delete p1; MovablePoint * mp1 = new MovablePoint(1, 2, 3, 4); mp1->print(); mp1->move(); delete mp1;

Substitution

A subclass instance inherits all the properties of the superclass, in the case of -inheritance. It can do whatever a superclass instance can do. This is known as a "is-a" relationship. Hence, you can substitute a subclass instance to a superclass reference.

Example

Using the above example of superclass and subclass ,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include <iostream> #include "MovablePoint.h" using namespace std; int main() { Point * ptrP1 = new MovablePoint(11, 12, 13, 14); cout << endl; delete ptrP1; MovablePoint mp2(21, 22, 23, 24); Point & p2 = mp2;p2.print(); cout << endl; Point p3 = MovablePoint(31, 32, 33, 34);p3.print(); cout << endl; }

Once substituted, it can invoke all the functions defined in the superclass, but CANNOT invoke functions defined in the subclass. This is because the reference is a superclass reference, which is not aware of subclass members.

Polymorphism

  1. A subclass instance can be substituted for a superclass reference.
  2. Once substituted, only the superclass' functions can be called, no the subclass'.
  3. If the subclass overrides a superclass function. 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 for functions that are meant to be polymorphic. In this case, if a superclass pointer is aiming at a subclass objects, and invoke a function that is overridden by the subclass, the subclass version will be invoked, instead of the superclass version. For example,

class Point { ...... virtual void print() const; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include <iostream> #include "MovablePoint.h" using namespace std; int main() { Point * ptrP1 = new MovablePoint(11, 12, 13, 14); cout << endl; delete ptrP1; MovablePoint mp2(21, 22, 23, 24); Point & p2 = mp2; p2.print(); cout << endl; Point p3 = MovablePoint(31, 32, 33, 34); p3.print(); cout << endl; }

The keyword determines which method is used if the method is invoked by a pointer (or reference). Without , the program chooses the method based on the pointer type; with , the program chooses the method based on the type of the object pointed-to.

Take note that virtual functions work on object pointers (and references), but not on regular objects.

If the subclass override a method inherited from its superclass, the usual practice is to declare the superclass method as . 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 function, the compiler selects the function that will be invoked at compiled-time (known as static binding). For virtual functions, the selection is delayed until the runtime. The function selected depends on the actual type that invokes the function (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 function, with implementation provided by subclass.
Using Virtual Functions
  • Using keyword on a superclass function makes the function virtual for the superclass, as well as ALL its subclasses.
  • If a virtual function is invoked using a pointer (or reference), the program uses the method defined for the object type instead of the pointer type. This is called dynamic binding or late binding, contrast to static binding during the compile time.
  • It is recommended that functions to be overridden in the subclass be declared in the superclass.
  • Constructor can't be , because it is not inherited. Subclass defines its own constructor, which invokes the superclass constructor to initialize the inherited data members.
  • Destructor should be declared virtual, if a class is to to be used as a superclass, so that the appropriate object destructor is invoked to free the dynamically allocated memory in the subclass, if any.
  • Friends can't be virtual, as friends are not class member and are not inherited.
  • If you override function in the subclass, the overridden function shall have the same parameter list as the superclass' version.
Upcasting and Downcasting

Normally, C++ does not allow you to assign an address of one type to pointer (or reference) of another type. For example,

int i = 8; double * ptr1 = &i;double & d = i;

However, a pointer or reference of superclass can hold a subclass object without explicit type cast:

MovablePoint mp(.....); Point * ptrP1 = &mp; Point & p2 = mp;

Converting a subclass to superclass reference or pointer is called upcasting. (Because in UML diagram, we often draw the superclass on top of the subclass, with an arrow pointing up from the subclass to the superclass.) Upcasting is always allow for -inheritance without the need for an explicit type cast, because -inheritance exhibits is-a relationship. A subclass object is a superclass object, because it inherits all the attributes and operations from the superclass, and can do whatever the superclass object can do.

The reverse operation, converting a superclass reference or pointer to subclass, is called downcasting. Downcasting requires explicit type cast.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <iostream> #include "MovablePoint.h" using namespace std; int main() { Point * ptrP1 = new MovablePoint(11, 12, 13, 14); ptrP1->print(); MovablePoint * ptrMP1 = ptrP1; // errorMovablePoint * ptrMP1 = (MovablePoint *) ptrP1; delete ptrP1; }
Operator dynamic_cast

C++ provides a new casting operator called , which returns a null pointer if the type cast fails. For example,

MovablePoint * ptrMP1 = dynamic_cast<MovablePoint *>(ptrP1);
Operator typeid

The operator returns a reference to an object of class (in header <typeinfo>, which contains information about the type of its operands. You can use 's member function to get the type name. For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 #include <iostream> #include <typeinfo> #include "MovablePoint.h" using namespace std; int main() { Point * ptrP1 = new MovablePoint(11, 12, 13, 14); cout << typeid(*ptrP1).name() << endl; MovablePoint * ptrMP1 = dynamic_cast<MovablePoint *>(ptrP1); cout << typeid(*ptrMP1).name() << endl; delete ptrP1; Point p2; cout << typeid(p2).name() << endl; MovablePoint mp2(1, 2, 3, 4); cout << typeid(mp2).name() << endl; }

Program Notes:

  • The number in front of the name gives the length of the string.

Pure Virtual Function and Abstract Superclass

A pure virtual function is specified by placing "" (called pure specifier) in its declaration. For example,

virtual double getArea() = 0;

A pure virtual function usually has no implementation body, because the class does not know how to implement the body. A class containing one or more pure virtual function is called an abstract class. You cannot create instances from an abstract class, because its definition 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 implementation to all the pure virtual functions. You can then create instances from the concrete subclass.

C++ allows implementation for pure virtual function. In this case, the simply make the class abstract. As the result, you cannot create instances.

Example: Shape and its Subclasses

[TODO] Description

Shape.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #ifndef SHAPE_H #define SHAPE_H #include <string> using namespace std; class Shape { private: string color; public: Shape(const string & color = "red"); string getColor() const; void setColor(const string & color); virtual void print() const; virtual double getArea() const = 0; }; #endif
Shape.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #include "Shape.h" #include <iostream> Shape::Shape(const string & color) { this->color = color; } string Shape::getColor() const { return color; } void Shape::setColor(const string & color) { this->color = color; } void Shape::print() const { std::cout << "Shape of color=" << color; }
Circle.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 #ifndef CIRCLE_H #define CIRCLE_H #include "Shape.h" class Circle : public Shape { private: int radius; public: Circle(int radius = 1, const string & color = "red"); int getRadius() const; void setRadius(int radius); void print() const; double getArea() const; }; #endif
Circle.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include "Circle.h" #include <iostream> #define PI 3.14159265 Circle::Circle(int radius, const string & color) : Shape(color), radius(radius) { } int Circle::getRadius() const { return radius; } void Circle::setRadius(int radius) { this->radius = radius; } void Circle::print() const { std::cout << "Circle radius=" << radius << ", subclass of "; Shape::print(); } double Circle::getArea() const { return radius * radius * PI; }
Rectangle.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 #ifndef RECTANGLE_H #define RECTANGLE_H #include "Shape.h" class Rectangle : public Shape { private: int length; int width; public: Rectangle(int length = 1, int width = 1, const string & color = "red"); int getLength() const; void setLength(int length); int getWidth() const; void setWidth(int width); void print() const; double getArea() const; }; #endif
Rectangle.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #include "Rectangle.h" #include <iostream> Rectangle::Rectangle(int length, int width, const string & color) : Shape(color), length(length), width(width) { } int Rectangle::getLength() const { return length; } int Rectangle::getWidth() const { return width; } void Rectangle::setLength(int length) { this->length = length; } void Rectangle::setWidth(int width) { this->width = width; } void Rectangle::print() const { std::cout << "Rectangle length=" << length << " width=" << width << ", subclass of "; Shape::print(); } double Rectangle::getArea() const { return length * width; }
Test Driver: TestShape.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 #include "Circle.h" #include "Rectangle.h" #include <iostream> using namespace std; int main() { Circle c1(5, "blue"); c1.print(); cout << endl; cout << "area=" << c1.getArea() << endl; Rectangle r1(5, 6, "green"); r1.print(); cout << endl; cout << "area=" << r1.getArea() << endl; Shape s1; // Cannot create instance of abstract class Shape Shape * s1, * s2; s1 = new Circle(6); s1->print(); cout << endl; cout << "area=" << s1->getArea() << endl; s2 = new Rectangle(7, 8); s2->print(); cout << endl; cout << "area=" << s2->getArea() << endl; delete s1; delete s2; Shape s3 = Circle(6); // error: cannot allocate an object of abstract type 'Shape' Circle c3(8); Shape & s3 = c3; s3.print(); cout << endl; cout << "area=" << s3.getArea() << endl; Circle c4(9); Shape * s4 = &c4; s4->print(); cout << endl; cout << "area=" << s4->getArea() << endl; }
Circle radius=5, subclass of Shape of color=blue area=78.5398 Rectangle length=5 width=6, subclass of Shape of color=green area=30 Circle radius=6, subclass of Shape of color=red area=113.097 Rectangle length=7 width=8, subclass of Shape of color=red area=56 Circle radius=8, subclass of Shape of color=red area=201.062 Circle radius=9, subclass of Shape of color=red area=254.469

[TODO] Explanation

Dynamic Binding vs. Static Binding

[TODO]

More On OOP

const Objects and const Member Functions

Constant Object: We can use to specify that an object is not mutable. For example,

const Point p1; Point p2; // p1 = p2; // error: const object cannot be reassigned p2 = p1;

Constant Member Functions: We declare a member function constant by placing the keyword after the parameter list. A member function cannot modify any member variable. For example,

int getX() const { return x; } void print() const { cout << "(" << x << "," << y << ")" << endl; }

A constant member function cannot modify data members too. For example,

void setX(int x) const { this->x = x; // ERROR! }

The constructor and destructor cannot be made , as they need to initialize data members. However, a object can invoke non- constructor. The property begins after construction.

A const object can invoke only const member functions

In C++, a object can only invoke member functions, and cannot invoke non- member functions. On the other hand, a non- object can invoke both and non- member functions. For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include <iostream> using namespace std; class Point { private: int x, y; public: Point(int x = 0, int y = 0) : x(x), y(y) { } int getX() const { return x; } int getY() const { return y; } void setX(int x) { this->x = x; } void setY(int y) { this->y = y; } void print() const { cout << "(" << x << "," << y << ")" << endl; } }; int main() { Point p1(5, 6); p1.setX(55); p1.print(); const Point p2(7, 8); p2.print(); p2.setX(55); // error: const object cannot invoke non-const member function }
Member Function Overloading with const

As an example, if you check the class' function (which returns the character at the given position), you will see two overloaded versions:

char & at (size_t pos); const char & at (size_t pos) const;

A non- string object will run the non- version, which returns a non- reference. The return reference can be used as the lvalue to modify the , e.g., . On the other hand, a object will invoke the member function, which returns a reference. A reference cannot be used as lvalue. For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> #include <string> using namespace std; int main() { const string s1("Apple"); string s2("Banana"); cout << s1.at(3) << endl; s2.at(0) = 'A'; cout << s2 << endl; s1.at(0) = 'B'; // error: assignment of read-only location }

const Data Member

You can declare a data member . A data member cannot be modified by any member function. It can only be initialized by the constructor using a special syntax called member initializer list. For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 #include <iostream> using namespace std; class Point { private: int x; const int y; public: Point(int x = 0, int y = 0) : x(x), y(y) { } int getX() const { return x; } int getY() const { return y; } void setX(int x) { this->x = x; } // void setY(int y) { this->y = y; } // error: assignment of read-only member void print() const { cout << "(" << x << "," << y << ")" << endl; } };

A member initializer list is placed after the parameter list, in the form of , .... Using triggers a compilation error due to the assignment into data member .

For object data member, you can use the member initializer list to trigger its constructor. member initializer list is also use to invoke superclass constructor from the subclass constructor.

"friend" Function and "friend" Class

friend Functions

A "friend" function of a class, marked by the keyword , is a function defined outside the class, yet its argument of that class has unrestricted access to all the class members (, and data members and member functions).

For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 #include <iostream> using namespace std; class Point { friend void set(Point & point, int x, int y); private: int x, y; public: Point(int x = 0, int y = 0) : x(x), y(y) { } void print() const { cout << "(" << x << "," << y << ")" << endl; } }; void set(Point & point, int x, int y) { point.x = x; point.y = y; } int main() { Point p1; p1.print(); set(p1, 5, 6); p1.print(); }

Notes:

  • A friend function is a regular function, NOT a member function of the class. Hence it is invoked without the dot operator in the form of , instead of for a member function.
  • The above example is meant for illustration. This operation is better served by a member function , instead of friend function.
  • The friend function prototype is provided inside the class declaration. You do not need to provide another prototype outside the class declaration, but merely provide its implementation.
  • Friend functions can enhance the performance by directly accessing the private data members, eliminating the overhead of going thru the public member functions.
  • Friend functions 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 functions.
  • Friend functions will not be inherited by the subclass. Friends can't be virtual, as friends are not class member.
friend Class

To declare all member functions of a class (says ) friend functions of another class (says ), declared "" in .

Friends are not symmetric. That is, if is a friend of , it does not imply that is a friend of . Friends are also not transitive. That is, if is a friend of , and is a friend of , it does not imply that is a friend of .

Use friend with care. Incorrect use of friends may corrupt the concept of information hiding and encapsulation.

The static Class Members

A static class member has only one copy, belonging to the class instead of the instances. All instances share the same storage for a class member. A members is referenced via scope resolution operator in the form of or .

  • It can be used to implement "global" class variables and functions, that can be used without creating instances of a class.
  • It can also be used to share information among all instances, e.g., a count on the number of instances created.

A function can only access variables, and cannot access non- variables. A static variable/function can be referenced without any instantiation (i.e., no instance is created).

Example (static Class Member): This example uses a data member to keep track of the number of instances created.

Point.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 #ifndef POINT_H #define POINT_H class Point { private: int x, y; static int count; public: Point(int x = 0, int y = 0); void print(); static int getCount(); }; #endif
Point.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 #include <iostream> #include "Point.h" using namespace std; int Point::count = 0;int Point::getCount() { return count; } Point::Point(int x, int y) : x(x), y(y) { ++count; } void Point::print() { cout << "Point number " << count << " @ (" << x << "," << y << ")" << endl; }

You cannot initialize the variable in the class declaration. This is because class declaration merely describe the memory allocation but does not actually allocate the memory. Instead, it is initialized outside the declaration as shown above. The initialization is kept in the implementation file, instead of header, so as not the repeat the same step when header file in included.

TestPoint.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 #include <iostream> #include "Point.h" using namespace std; int main() { Point p1; p1.print(); cout << Point::getCount() << " instances created" << endl; Point p2(1, 2); p2.print(); cout << Point::getCount() << " instances created" << endl; Point p3(3); p3.print(); cout << Point::getCount() << " instances created" << endl; }

Program Notes:

  • A data member retains this value throughout its life span.
  • To reference a class member, you need to use . You CANNOT invoke member function from an instance, such as .
  • A data member can be accessed by and non- member functions. However, a function member can only access data members, and CANNOT access non- data members. For example, int Point::getCount() { cout << "(" << x << "," << y << ")" << endl; // error: invalid use of member 'Point::x' in static member function return count; }

More On Inheritance

Multiple Inheritance

A class derived from more than one base classes.

[TODO]

Virtual Inheritance

A base class instance is shared by multiple derived class instances.

[TODO]

Object with Dynamically Allocated Data Members

Implicitly-generated Special member Functions

C++ compiler automatically generates the following special member functions if they are required in your program:

  • A default constructor if you did not define any constructor.
  • A copy constructor if you did not define one.
  • An assignment operator if you did not define one.
  • An address-of operator if you did not define one.
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 class, the following default constructor will be generated:

Point::Point() {}

The default constructor does not initialize the data members. For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> using namespace std; class Point { private: int x, y; public: void print() const { cout << "(" << x << "," << y << ")" << endl; } }; int main() { Point p1; p1.print(); }

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 compilation error For example,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 #include <iostream> using namespace std; class Point { private: int x, y; public: Point(int x, int y) : x(x), y(y) { } void print() const { cout << "(" << x << "," << y << ")" << endl; } }; int main() { Point p1; // error: no matching function for call to 'Point::Point()' }

A constructor with arguments can be treated as a default constructor if all arguments have a default value. For example,

point(int x = 0, int y = 0) : x(x), y(y) { }
Copy Constructor

A copy constructor is used to construct a new object by copying the given object. It take a reference of an object of the same class, as follows:

ClassName(const ClassName &);

The copy constructor is used in the following situations:

Point p1(p2); Point p1 = p2; Point p1 = (Point)p2; Point * ptrP1 = new Point(p2);

In addition, when an object is passed by value into a function, and when a function 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 function, which avoids the overhead of copying.]

The default copy constructor performs a memberwise copy of all the non- 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. Static 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 allocation 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 automatically overloading the assignment operator, as follows:

ClassName & operator=(const ClassName &);

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. Static members are not copied. Again, for pointers, the value of pointer is copied, but no dynamic allocation is performed to duplicate the contents of the pointer (shadow copying).

Dynamic Memory Allocation of Object Data Member

In C++, you can allocate memory for object during runtime, instead during compile-time, using operators and . However, you are responsible for memory management, and are required to free the memory via and to prevent memory leak. If you introduce in your constructor, you need to use in destructor to free the memory.

If you use (or ) to dynamically allocate memory in the constructor to object data member pointers, for example,

class ClassName { private: T * pObj; public: ClassName(...) { pObj = new T(...); .... } ~ClassName() { delete pObj; } ClassName & ClassName(const ClassName &); ClassName & operator=(const ClassName &); ...... }
  • You should use (or ) in the destructor to free the dynamic memory allocated.
  • If you have more than one constructors, all constructors should be compatible 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 initializes 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.
Using Object Pointer
  • Declare an object pointer: T * pObj;
  • Either initialize the pointer to an existing object, or dynamically allocate an object. pObj = &obj; pObj = new T(...);
  • Use member-of () operator to refer to its class members, e.g. .
  • Use dereferencing () operator to get its content, e.g., .
Link to "C++ References & Resources"

0 thoughts on “C++ Inheritance Programming Assignment

Leave a Reply

Your email address will not be published. Required fields are marked *