0% found this document useful (0 votes)
7 views29 pages

Unix 6 and 7_objects and Classes_ Constructors (1)

This document provides an overview of object-oriented programming concepts, focusing on classes and objects in C++. It explains how to declare classes, define member functions, create objects, and access class members, including the use of access specifiers. Additionally, it covers the distinction between base and derived classes, as well as examples of class implementation in C++.

Uploaded by

antomotongori
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views29 pages

Unix 6 and 7_objects and Classes_ Constructors (1)

This document provides an overview of object-oriented programming concepts, focusing on classes and objects in C++. It explains how to declare classes, define member functions, create objects, and access class members, including the use of access specifiers. Additionally, it covers the distinction between base and derived classes, as well as examples of class implementation in C++.

Uploaded by

antomotongori
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

UNIT SIX: OBJECTS AND CLASSES

Learning outcomes

Upon completing this topic you should be able to:

 Declare a class

 Differentiate between member variables and member functions

 Define member functions

 Create objects from a class

 Access data members

6.1 Introduction to Classes


Object

At the heart of object-oriented programming is the object. An object is an entity -an instance of a data type
-that has structure and state. Each object defines operations that may access or manipulate that state.
Class
A class is a user defined data type, which holds its own data members and member functions, which can be
accessed and used by creating an instance of that class. A class is like a blueprint for an object.
Classes are fundamental building blocks of object-oriented programs. A class binds data and functions
together. The data and functions of a class are its members.

Example:

Consider the Class of Cars. There may be many cars with different names and brand but all of them will
share some common properties, e.g., all of them will have 4 wheels, Speed Limit, Mileage range etc. So
here, Car is the class and wheels, speed limits, mileage are their properties (attributes).

 A Class is a user defined data-type which has data members and member functions.

Page 1 of 29
 Data members are the data variables
 Member functions are the functions used to manipulate these variables. These data members and
member functions together define the properties and behavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage etc and member
functions can be apply brakes, increase speed etc

Base class v derived class


 A base class is a class, from which other classes are derived. It facilitates the creation of other classes
that can reuse the code implicitly inherited from the base class (except constructors and destructors).
A base class may also be called parent class or superclass

 Derived Class: A class that is created from an existing class. It inherits all members and member
functions of a base class. The derived class can have more functionality with respect to the Base
class and can easily access the Base class. A Derived class is also called a child class or subclass.
Defining Class and Declaring Objects
A class is defined in C++ using keyword class followed by the name of class. The body of class is defined
inside the curly brackets and terminated by a semicolon at the end.

6.2 Declaring a class

Specifying the data members and member functions of a class is known as declaring a class.

The class definition begins with class keyword followed by the name of the class. The name of a class is an
identifier and it is not supposed to be a reserved word. The body of a class is enclosed within the opening
curly brace ({) and closing curly brace (}). The closing curly brace is terminated by a semi-colon (;). The
body of a class consists of data members and member functions.

The syntax for defining a class is:

Page 2 of 29
Class class_name

private:

data_type number1;

data_type number2;

………….

data_type numbern;

public:

method function1;

method function2;

……………………..

};

Page 3 of 29
Example :

Class Rectangle{

private:

int length;

int width;

public:

void print_dimension(void);

};

Declaring Objects: When a class is defined, only the specification for the object is defined; no memory
or storage is allocated. To use the data and access functions defined in the class, you need to create objects.
Syntax:

Page 4 of 29
ClassName ObjectName;

6.3 Defining Member Functions

A class in C++ consists of its members. These members can be either data or functions. The functions are
called member functions. Each instance of a class is an object. Each object contains the data components
specified in the class (unless the data components are static). A member function is used to act on an object.
Member functions are also called methods.

The data members and member functions details are controlled using private, public
and protected keywords. Private, public and protected keywords are also referred to as
access specifiers/modifiers and are always followed by a colon (:).

 The private section of a class has data members and member functions that are
available only within the class (except by friend functions).

 The public section makes the data members and member functions within it to
be available to all class members and to the other classes’ members and
applications.

 The protected section has data members and member functions that are
available to the class itself and any other derived class.
The beginning of each section is marked by keywords private: public: and protected:
NB: By default data members and member functions are private.
Normally the data members are put in the private section of a class and the member
functions are put in the public section.

There are two ways of defining member functions:

a) Inside the class definition

b) Outside the class definition

Page 5 of 29
a) Definition of a member function outside a class definition

The member functions declared within a class can be defined outside a class.
The definitions of these functions are just the same as definition of the normal functions
(functions that are not members of a class). But unlike normal functions, member
functions defined outside a class definition are qualified with the name of the class that
they belong to. The name of the class and the member function are separated using the
scope resolution operator (: :).

The syntax of defining a member function outside a class is:


return-type class-name :: function-name (parameter list) { function body }

For instance, consider the print_dimension function declared in the Rectangle class
above. It may be defined as follows:

void Rectangle :: print_dimension(void)

{
cout<< “The Length is:”<<length <<”cm\n” <<”The width is :” <<width <<”cm\n”

<<endl;

b) Definition a member function inside a class definition

Member functions can be defined within a class definition. Still consider the print_dimension()
function declared in the class Rectangle above. This function can be defined in the class as shown
below.

class Rectangle

{
private:

int length;

int width;
public:
Page 6 of 29
void funt()

)
{

cout<< “The Length is:”<length << “cm\n” << “The width is :” <<width < “cm\n”<<endl;

};

6.4 Creating objects from a class


Once a class has been defined, it can be instantiated. Instantiating a class means creating an object from a
class.
The objects that are created are the ones that are used to call member functions of the class.
A class that can be instantiated is referred to as a concrete class. There are those classes that can not be
instantiated. Such classes have at least one member a pure virtual function. Such classes are referred to as
abstract classes.
The syntax for instantiated a class is:

a) Form 1

class-name variable-name;
e.g.

Rectangle rect1;
b) Form 2

class-name variable-name(arguments);
e.g.

Rectangle rect2(4, 5);

Page 7 of 29
The above two statements create class variables rect1 and rect2 of type Rectangle. A class variable is an
object. In that case rect1and rect2 are objects of type Rectangle

5.5 Accessing class members


All private data members are accessible only by class member functions (this restriction does not apply to
friend functions).
It is illegal to have a statement for example within the main method that accesses the value stored in data
member.
External functions access private data members by calling public members of a class. The syntax for doing
this is object-name. function-name( arguments);
This is what is referred to as message passing. The receiver of the message is object-name. The name of the
message is function-name. The information that is passed to the object in order for the object to respond to
the message is “arguments” E.g. rect1.print_dimension();

Below is an example of a C++ program that is made of a class

/* ————————————————————————————————

Rectangle.cpp

This program demonstrates the use classes in a C++ program

—————————————————————————————————-
*/
#include<iostream>
using namespace std;

class Rectangle{
private:

int length;
int width;
public:

Rectangle(int l, int w);


void print_dimension(void);

Page 8 of 29
};

int main(void)

Rectangle rect1(5,3);
rect1.print_dimension();

return 0;

}
/* ————————————————————————————————

—–

Definition of Rectangle member function

—————————————————————————————————-

*/

Rectangle :: Rectangle(int l, int w)

length=l;
width=w;

}
/* ————————————————————————————————

—–

Definition of print_dimension member function

—————————————————————————————————-

*/

void Rectangle :: print_dimension(void)

Page 9 of 29
cout<<”The Length is: “<<length <<”cm\n” <<”The width is : “<<width <<”cm\n”

<<endl;

If you compile and execute this program, the output is The Length is: 5cm The width is : 3cm

Example
To access public members of a class, we use the (.)dot operator.
These are members marked with public access modifier.

#include <iostream>
using namespace std;

class Phone {
public:

double cost;
int slots;

};
int main() {

Phone Y6;
Phone Y7;

Y6.cost = 100.0;
Y6.slots = 2;

Y7.cost = 200.0;
Y7.slots = 2;

cout << "Cost of Huawei Y6 : " << Y6.cost << endl;


cout << "Cost of Huawei Y7 : " << Y7.cost << endl;
Page 10 of 29
cout << "Number of card slots for Huawei Y6 : " <<
Y6.slots << endl;
cout << "Number of card slots for Huawei Y7 : " <<
Y7.slots << endl;
return 0;

Additional Examples for Classes

Example

Write a C++ program to find sum of two integer using class and object.

#include <iostream>
using namespace std;
//class definition
class Numbers
{
private:

int a; int b;
public:
//member functions declaration
void readNumbers(void);
void printNumbers(void);
int calAddition(void);
};

//member function definitions

void Numbers::readNumbers(void)
Page 11 of 29
{

cout<<"Enter first number: ";


cin>>a;
cout<<"Enter second number: ";
cin>>b;
}
void Numbers::printNumbers(void)

cout<<"a= "<<a<<",b= "<<b<<endl;

int Numbers::calAddition(void)

return (a+b);

//main program
int main()
{
Numbers num; //declaring object
int add; //variable to store addition

//take input
num.readNumbers();
//find addition
add=num.calAddition();
//print numbers
num.printNumbers();
//display addition
Page 12 of 29
cout<<"The sum is "<<add<<endl;
return 0;
}

Example 2

#include <iostream>

using namespace std;

class Box {

public:

double length; // Length of a box

double breadth; // Breadth of a box

double height; // Height of a box

};

int main() {

Box Box1; // Declare Box1 of type Box

Box Box2; // Declare Box2 of type Box

double volume = 0.0; // Store the volume of a box here

// box 1 specification

Box1.height = 5.0;

Page 13 of 29
Box1.length = 6.0;

Box1.breadth = 7.0;

// box 2 specification

Box2.height = 10.0;

Box2.length = 12.0;

Box2.breadth = 13.0;

// volume of box 1

volume = Box1.height * Box1.length * Box1.breadth;

cout << "Volume of Box1 : " << volume <<endl;

// volume of box 2

volume = Box2.height * Box2.length * Box2.breadth;

cout << "Volume of Box2 : " << volume <<endl;

return 0;

/ C++ program to demonstrate accessing of data members

Page 14 of 29
#include <bits/stdc++.h>

using namespace std;

class ClassName

// Access specifier public:

// Data Members

string Myname;

// Member Functions()

void printname()

cout << "My name is: " << Myname;

};

int main() {

// Declare an object of class names

names obj1;

// accessing data member

obj1. Myname = "Alex";

// accessing member function

Page 15 of 29
obj1.printname();

return 0;

Example 3

Write a C++ program to find sum of two integer using class and object.

#include <iostream>

using namespace std;

//class definition class Numbers

private:

int a; int b;

public:

//member function declaration void readNumbers(void);

void printNumbers(void);

int calAddition(void);

};

Page 16 of 29
//member function definitions

void Numbers::readNumbers(void)

cout<<"Enter first number: "; cin>>a;

cout<<"Enter second number: "; cin>>b;

void Numbers::printNumbers(void)

cout<<"a= "<<a<<",b= "<<b<<endl;

int Numbers::calAddition(void)

return (a+b);

//main function

int main()

//declaring object

Numbers num;

Page 17 of 29
int add; //variable to store addition

//take input

num.readNumbers();

//find addition

add=num.calAddition();

//print numbers

num.printNumbers();

//print addition

cout<<"Addition= "<<add<<endl; return 0;

Example 4

In the code example below, the only members of rect that cannot be accessed from outside the class are
width and height, since they have private access and they can only be referred to from within other
members of that same class.

// classes example

#include <iostream>

using namespace std;

class Rectangle {

int width, height; public:

void set_values (int,int);

int area() {return width*height;}


Page 18 of 29
};

void Rectangle::set_values (int x, int y) { width = x;

height = y;

int main ()

Rectangle rect;

rect.set_values (3,4);

cout << "area: " << rect.area();

return 0;

}
6.6 Class Member Functions

 Virtual member functions


Are resolved dynamically (at run-time). That is, the member function is selected dynamically based on the
type of the object, not the type of the pointer/reference to that object. This is called "dynamic binding."
...

class Account{
public:

virtual string getType()

{ return "Generic Account"; };

};

Page 19 of 29
public:
virtual string getType() { return "Current Account"; };

};

class Deposit: public Account{

public:
virtual string getType() { return "Deposit Account"; };

};

int main()

// Note that all pointers have the static type Account


Account *a = new Account();
Account *b = new Current();
Account *c = new Deposit();
cout << "Pointer a Displayed: " << a->getType() << endl; cout
<< "Pointer b Displayed: " << b->getType() << endl; cout <<
"Pointer c Displayed: " << c->getType() << endl;
}
 Non-virtual member functions are resolved statically. That is, the member function is selected
statically (at compile-time) based on the type of the pointer (or reference) to the object.
……..

class Account{
public:
string getType()
{ return "Generic Account"; };
Page 20 of 29
};

class Current: public Account{

public:

string getType() { return "Current Account"; };

};

class Deposit: public Account{

public:
string getType() { return "Deposit Account"; };

};

int main()

Account *a = new Account();


Account *b = new Current();
Account *c = new Deposit();
cout << "Pointer a Displayed: " << a->getType() << endl; cout
<< "Pointer b Displayed: " << b->getType() << endl; cout <<
"Pointer c Displayed: " << c->getType() << endl;
}
 Friend function - is a function that is given the same access as methods to private and protected
data. A friend function is declared by the class that is granting access, so friend functions are part
of the class interface, like methods. To declare a function as a friend of a class, precede the
function prototype in the class definition with keyword friend.
Example: Write a C++ statement that declare a function friend.

class Box {
Page 21 of 29
double width;
public:

double length;

friend void printWidth( Box box );

void setWidth( double wid );


};

6.7 Revision Questions

i. Differentiate between function declaration and function definition

ii. Differentiate data members and member functions


iii. Differentiate Rectangle rect1; and Rectangle rect2()

iv. Explain the use private, protected and public keywords

v. Explain the difference between internal and external definition of member functions

Page 22 of 29
UNIT SEVEN: CONSTRUCTORS AND DESTRUCTORS

Learning outcomes

Upon completing this topic you should be able to:

 Differentiate constructor and destructor


 List characteristics of constructor and destructor
 Use constructors and destructors

7.1 Constructors

A constructor is a member function that is used for creating objects and initializing the states of the objects.

A constructor has the following characteristics:

• Its name is the same as the name of the class within which it has been declared

• It is called automatically

• It does not have return type

• It is always declared within the public section of a class

• It is not inherited. A constructor cannot be made virtual

• The address of the memory location occupied by a constructor cannot be referenced

7.2 Declaration of Constructors

A constructor is declared and defined as follows:

Page 23 of 29
class Rectangle

private:

int length;

int width;

...

public:

Rectangle(int l, int w); //declaration of constructor

...

};

//definition of constructor

Rectangle::Rectangle(int l, int w)

length=l;

width=w;

7.3 Calling Constructors

Since a constructor is always declared within the public section of a class, it is accessible from external
functions (these are functions that are not members of the class that has the class).
Page 24 of 29
For example the main method can call the constructor in the Rectangle class above as shown below.

Rectangle rect1(6, 5);

This statement is a call to Rectangle constructor in a class called Rectangle. The constructor is also passed
two integer values, i.e. 6 and 5. The constructor will construct the object and 6 and 5 values will be used
as the initial state of the object. The object that will be created will be referenced by rect1 variable. If we
now want to pass a message to the object that has been created in Rectangle class, we have to use rect1 to
refer to the object as shown below rect1.find_area(); rect1 is our reference to the object created and
find_area() is the message that we are passing to our object. rect1 refers to the object created.

7.4 Types of Constructors

There are three types of constructors:

• Default constructors

• Copy constructors

• Parameterized constructors

a) A Default Constructor

A default constructor is a constructor that is not passed any arguments when it is called. A default
constructor can be created automatically by the compiler. For example, the default constructor for
Rectangle class above is:

class Rectangle

private: . . .

public:

Rectangle();
Page 25 of 29
...

};

//definition of default constructor

Rectangle::Rectangle()

Note that the body of this constructor is empty. Now if we have a statement shown below within the main
method

int main(void)

Rectangle rect1;

...

return 0;

Statement Rectangle rect1; in the above main method is a call to the default. In that case if the Rectangle
class do not have the default constructor the compiler will create one automatically.

b) Parameterized constructors

Parameterized constructors are constructors that are passed arguments when they are called. Unlike default
constructors, parameterized constructors are not created automatically by the compiler if they are not
defined in a class. And these constructors must be defined. For example:

class Rectangle

Page 26 of 29
{

private: int length;

int width;

...

public:

Rectangle(int l, int w);

...

};

//definition of a parameterized constructor

Rectangle::Rectangle(int l, int w)

{ length=l; width=w; }

There are two ways of passing arguments to parameterized constructors when they are called: by calling
the constructor explicitly and by calling the constructor implicitly. For example Rectangle rect1=
Rectangle( 6, 5); //explicit call Rectangle rect1(6, 5); //implicit call Implicit call is the one that is normally
used.

c) Copy constructors

Copy constructors are constructors that used to create and initialize an object using another object. For
example Rectangle rect1(6, 5); //a call to a parameterized constructor Rectangle rect2(rect1); // a call to a
copy constructor to create and initialized rect2 object //using rect1 object

Page 27 of 29
7.5 Destructors

A destructor is a member function that is used to free a location that is held by an object for use by another
object.

An object is deleted when the flow of control leaves the scope within which it has been created.

A destructor has the following properties

 Its name is the same as the name of the class


 Its name is preceded by a tilde (~) character
 It is not passed arguments and it does not have return type not even void
 It is called implicitly
 A class can have only one destructor
 A destructor can not be overloaded

For example

Rectangle::~Rectangle()

cout<< “An object has been destroyed”<<endl;

Note that just like other member functions, constructors can have default arguments and they can be
overloaded.

7.6 Revision Questions

i. Differentiate a constructor and a destructor


ii. List any FOUR characteristics of a destructor
Page 28 of 29
iii. Explain why a constructor is public and has no return type
iv. Differentiate a default constructor, a copy constructor and parameterized constructor
v. Explain the difference between the following two statements:
Car myCar(200); and Car yourCar;

Page 29 of 29

You might also like