0% found this document useful (0 votes)
4 views49 pages

Bui-Csc 201 Lecture Note 3

The document provides an overview of objects and classes in C++, detailing the structure and functionality of classes, including data members and member functions. It explains access specifiers (public, private, protected), the concept of friend functions, constructors, and the different types of constructors (default, parameterized, and copy). Additionally, it covers member functions, function overloading, and the rules for using default arguments.

Uploaded by

ooafonrinwo
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)
4 views49 pages

Bui-Csc 201 Lecture Note 3

The document provides an overview of objects and classes in C++, detailing the structure and functionality of classes, including data members and member functions. It explains access specifiers (public, private, protected), the concept of friend functions, constructors, and the different types of constructors (default, parameterized, and copy). Additionally, it covers member functions, function overloading, and the rules for using default arguments.

Uploaded by

ooafonrinwo
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/ 49

Prepared by : Adeniyi A.

Emmanuel
Objects & Classes in C++
 A class is a data structure or a user-defined data type
 It contains data members which describe the
properties of the object, and member functions or
methods, which describe the operations that can be
performed on data members of the class.
 E.g.: In a class of students, the properties/characteristics
of the students form the data members of the class
while what the students are expected to do form the
behavior/functions/methods of the class
 Therefore, a class is a blueprint/template that defines the
characteristics (data members) and behavior
(member functions) of the instance of a class
Objects & Classes in C++
 An object is called an instance of a class
 It is a variable that has been defined to use the
members and methods defined in a class definition
 When classes are defined, memory are not assigned to
the classes but when objects are created, memory
locations are assigned to the objects.
 They process of creating an object is called object
instantiation
 Objects are initialized using special class functions
called Constructors.
 And whenever the object is out of its scope, another
special class member function called Destructors is
called, to release the memory already allocated to the
object.
Access Specifiers in C++
 One of the important concept of OOP is data hiding,
i.e., a nonmember function cannot access an object's
private or protected data.
 Access specifiers in C++ determines when, where and how
data members and methods in a class can be accessed or
made available.
 They could be:
 Public:
 Private:
 Protected:
 Access specifiers in the program are followed by a colon (:)
 You can use either one, two or all three specifiers in the
same class to set different boundaries for different class
members
Public Access Specifiers in C++
 Public means that class members and functions can be used
from outside of a class by any function or other classes
 Hence there are chances that the member of a class can change
or manipulate other members of a another class
 Therefore, the key members of a class should not be declared
public.

 class Person
 {
 public: // public access specifier
 int x; // Data Member Declaration
 void display(); // Member Function declaration
 }

 You can access public data members or function directly by


using dot operator (.)
Public Access Specifiers in C++

class Person
{
public: //access control
string firstName;//these data members
string lastName;//can be accessed
};
Private Access Specifiers in C++
 Private keyword means that class members and functions
can be used only inside the class and by friend functions
and classes
 Data members and functions cannot be accessed by other
classes or functions
 An attempt to access the data members and functions will
yield a compile time error.
 By default class variables and member functions are
private.
 class PrivateAccess
 {
 private: // Private Access Specifier
 int x; // Data Member Declaration
 void display(); // Member Function declaration
 }
Private Access Specifiers in C++
class Person
{
public: //access control
string firstName;//these data members
string lastName;//can be accessed
private:
string address; //these members can be accessed inside the class
long int insuranceNo; //and by friend classes/functions
};
Protected Access Specifiers in C++
 Protected class members and functions can be used
inside its class but are inaccessible outside the class.
 However, they can be accessed by any subclass of that class
as well as friend functions and classes
class ProtectedAccess
{
protected: // Protected Access Specifier
int x; // Data Member Declaration
void display(); // Member Function declaration
}
Protected Access Specifiers in C++
 Protected class members and functions can be used
inside its class but are inaccessible outside the class.
 However, they can be accessed by any subclass of that class
as well as friend functions and classes
class ProtectedAccess
{
protected: // Protected Access Specifier
int x; // Data Member Declaration
void display(); // Member Function declaration
}
Friend Functions in C++
 It is possible for a class to have access to the members of
another class OR for a function to have access to the
members of another class if such were defined to be a
friend.
 A friend function of a class is defined outside that class'
scope but it has the right to access all private and
protected members of the class.
 Even though the prototypes for friend functions appear in
the class definition, friends are not member functions.
Friend Functions in C++
class WithFriend
{
int i;
public:
friend void fun(); // function declared as friend
};

void fun() // friend function definition


{
WithFriend wf;
wf.i=10; // Access to private data member
cout << wf.i;
}

int main()
{
fun(); //Can be called directly
}
Friend Functions in C++
 Similarly we can also make function of other class as
friend, or we can also make an entire class as friend
class
 When we make a class a friend, all its member functions
automatically become friend functions
 Friend Functions is a reason, why C++ is not called a pure
Object Oriented language. Because it violates the concept
of Encapsulation/ data binding.
Friend Functions in C++
class Other // a class definition
{
void fun();
};

class WithFriend // another class definition


{
private:
int i;
public:
void getdata(); // Member function of class WithFriend
friend void Other::fun(); // making function of class Other as a friend
friend class Other; // making the complete class as a friend
};
Class Definition in C++
 Class definition simply connotes specifying the
members and functions of a class as well as their access
specifiers.
 It gives the structure or a blueprint of what the object
of that class will contain and what operations can be
performed on that object
 No storage is assigned when we define a class except
when we declare the objects
 Therefore, a class definition must contain a class
keyword, className, access specifiers, data
members and member functions
Defining Class and Declaring Objects
 class Student
{
Private:
int level, room_no;
string name, matric_no;
float gp, cgp;
public:
void display();
void register();
} postGrad, underGrad, preDegree;
OR
int main ()
Student postGrad, underGrad, preDegree;
Accessing Data Members of a Class
 Accessing a data member depends solely on the access
specifier of the data members.

 If its public, then the data member can be easily accessed


using the direct member access (.) operator with the
object of that class.

 If the data member is defined as private or protected, then


we will have to create special public member functions to
access, use or initialize the private and protected data
members outside the class.
Accessing Public Data Members of a Class
class Student
{
public:
string name;
int level;
void register (void);
};
int main()
{
Student agric_stud, comp_stud;
cout <<“Supply Student Name “<<endl;
cin>> agric_stud.name;
cout <<“Supply Student Level “<<endl;
cin>> agric_stud.level;
cout <<“Student Name: "<< agric_stud.name << endl;
cout <<“Student Level: "<< agric_stud.level << endl;
}
Accessing Protected Data Members of a
Class
 Protected data members can be accessed directly using dot
(.) operator inside the subclass of the current class.
 Outside the subclass, they will be accessed like private
data member.
Member Functions in Classes
 Member functions are functions that are declared inside class definitions
and works on the data members of the class.

 They could be getter/Accessor function or setter/mutator functions

 Mutator functions are used to read values into data members while
accessor functions are used to manipulate data sored in data members

 The definition of member functions can be inside or outside the class


definition.

 If the member function is defined outside the class, then we have to use
the scope resolution :: operator along with class name and function
name as in int Cube :: getVolume() where Cube is a class name and
getVolume is the function name.
Member Functions Definition inside
the Class
class Cube
{
public:
int side;
int getVolume() // Declaring function getVolume
{ //with no argument
return side*side*side; //returns volume of cube
}
};
Member Functions Definition inside
the Class
 But if we plan to define the member function outside the class
definition then we must declare the function inside class
definition and then define it outside.
class Cube
{
public:
int side;
int getVolume(); // member function declaration
};
int main ()
{
int Cube :: getVolume() // member function definition
//outside the class
{
return side*side*side;
} }
Overloaded Functions in Classes
 It is possible to have overloaded member functions in classes

 If any class has multiple functions with the same name but
different parameters then they are said to be overloaded.

 Function overloading allows you to use the same name for


different functions, to perform, either same or different
task in the same class.

 This could be achieved in two ways:

 By changing number of Arguments.

 By having different data types of the arguments


Overloading Functions By changing
number of Arguments
 These overloaded functions have the same name but
different number of parameters of the same data type.
int sum (int x, int y)
{ int main()
cout << x+y; {
} sum (10,20); // Overloaded Function
//with 2 parameter will
int sum (int x, int y, int z) //be called
{
cout << x+y+z; sum(10,20,30); // Overloaded
//Function with 3
} //parameters will be
//called
}
Overloading Functions By having different
Types of Argument
 These overloaded functions have the same name and same
number of parameters, but different data types.
int sum (int x, int y)
{
cout<< x+y;
}
double sum (double x, double y)
{
cout << x+y;
}
int main()
{
sum (10,20);
sum(10.5,20.5);
}
Default Arguments
 When you assign a default value for a parameter while
declaring the function, then the parameter is said to be a
default argument
sum(int x, int y=0)
{
cout << x+y;
}

y is a default parameter
Rules for using Default Arguments
 Rule 1: Only the last argument must be given default value.
You cannot have a default argument followed by non-default
argument
sum (int x,int y);
sum (int x,int y=0);
sum (int x=0,int y); // This is Incorrect
 Rule 2: Once an argument is a default argument, subsequent
arguments after must be a default argument
sum (int x,int y=0);
sum (int x,int y=0,int z); // This is incorrect
sum (int x,int y=10,int z=10); // Correct
Rules for using Default Arguments
 Rule 3: You can assign any default value to an argument once
its compatible with its datatype.
 Rule 4: Placeholder arguments can also be used with default
arguments.
 Placeholder arguments are arguments without an identifier
 E. g. void sum (int, int);
 void sum (int, int=0);
Programming Task
Constructors
 No storage or values are allocated to data members when
they are defined but immediately an object is instantiated,
the compiler assigns memory locations and initial values to
data members.

 Compiler does this using special member functions called


Constructors.

 However, programmers can also assign initial values to data


members using Constructors
Rules Guiding the use of Constructors

 A constructor should have the same name as that of the


class.

 It should be a public member.

 A constructor does not have any return values.

 A constructor can be overloaded


Syntax

 class class_name
{
 public:
 class_name(); // a constructor with no arguments
 // Other Members Declaration
}
Defining a Constructor
Constructors can be defined inside the class definition or outside
class definition using class name and scope resolution operator
::
class Example
{
int a, b;
public:
Example (); //Constructor declaration
Void display ()
{ cout << “values: ”<<a<< “\t” <<b; }
};

Example :: Example () // Constructor definition outside the class


{
a=10; b=20;
}
Constructor Definition inside a Class
class Example
{
int a, b;
public:
Example () // Constructor definition inside the class
{
a=10; b=20;
}
Void display ()
{ cout << “values: ”<<a<< “\t” <<b; }
};
Types of Constructors

 Constructors are of three types :

i. Default Constructor

ii. Parameterized Constructor

iii. Copy Constructor


Default Constructor
 This is a constructor without an argument or parameter.
class Cube
{
int side;
public:
Default Constructor
Cube()
{
side=10; Constructor definition
}
};

int main()
{
Cube c;
cout << c.side;
}
Parameterized Constructor
#include<iostream>
#include<conio.h>
using namespace std;
class Example
{
int a, b;
public:
Example (int x, int y) // Constructor with Parameters
{ a = x;
b = y; }
void Display()
{ cout << "\nValues :" << a << "\t" << b; }
}
Copy Constructor
 Copy Constructor is a type of constructor which is used to
create a copy of an already existing object of a class type.
 The compiler automatically calls the copy constructor
whenever:
i. an object is copied by means of a declaration initialization;
ii. an object is passed by value to a function;
iii. an object is returned by value from a function.
It has the syntax:
Classname (const classname &objectname)
{
....
}
#include<iostream>
#include<conio.h>
using namespace std;
class Example
{
int a, b;
public:
Example (int x, int y) //Normal Constructor with Argument
{ a = x;
b = y; }
Example (const Example &obj) // Method 1: Copy Constructor with Obj Argument
{ a = obj . a;
b = obj . b;
}
void Display()
{ cout << "\nValues :" << a << "\t" << b; }
}
int main()

{
Example Object (10, 20); // Normal Constructor Invoked
Example Object2(Object); // Copy Constructor Invoked - Method 2
Example Object3 = Object; // Copy Constructor Invoked - Method 3
Object.Display();
Object2.Display();
Object3.Display();
getch();
return 0;
}
Constructor Overloading
 Just like other member functions, constructors can also be
overloaded.
 When you have both default and parameterized constructors
defined in your class you are having Overloaded
Constructors, one with no parameter and other with
parameter.
#include<iostream>
#include<conio.h>
using namespace std;
class Example
{
int a, b;
public:
Example ( ) // Constructor without Argument
{ a = 50;
b = 100; }
Example (int x , int y ) // Constructor with Argument
{ a = x;
b = y;
}
void Display()
{ cout << "\nValues :" << a << "\t" << b; }
}
Destructors
 Destructor is a special class function which destroys the
object as soon as the scope of the object ends or deleted
 The syntax for destructor is same as that for the constructor,
the class name is used for the name of destructor, with a
tilde ~ sign as prefix to it.
 Destructors don’t have arguments and return type.
 Its syntax is:
Class class_name
{
Public:
~class_name() // Destructor
{
}
}
class BaseClass
{
Public:
BaseClass ()
{
cout << "Constructor called";
}
~BaseClass() {
cout << "Destructor called";
} };
int main() {
BaseClass obj1; // Constructor Called
int x=1
if (x)
{
BaseClass obj2; // Constructor Called
} // Destructor Called for obj2 (obj2 is no more needed)
} // Destructor called for obj1 (obj1 is no more needed)
Operator Overloading in C++
 Operators have the same meaning when used with variables of
basic data types like int, float, double etc
 However, you need to redefine the way operators work whenever it
is used with user-defined data types like structures and classes.
 The process of redefining how operators will work when used with
user-defined data types like classes is called OPERATOR
OVERLOADING
 Therefore, overloaded operator is used to perform operation on
user-defined data type only.
 Not all operators can be overloaded in C++; operators that can not
be overloaded includes:
 Scope resolution operator::
 Member selector operator .
 Member pointer selector *
 Ternary operator ?:
 Preprocessor symbols # and ##
Operator Overloading Syntax

Operator Overloading Syntax

 Given that the x coordinate of the sum of two points is the

sum of the x coordinates, and the y coordinate is the sum of

the y coordinates, use the concept of operator overloading to

implement the sum of two points such that (x1; y1) + (x2; y2)

= (x1+x2; y1+y2)
Operator Overloading Syntax

Inheritance in C++

You might also like