Bui-Csc 201 Lecture Note 3
Bui-Csc 201 Lecture Note 3
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
}
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
};
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();
};
Mutator functions are used to read values into data members while
accessor functions are used to manipulate data sored in data members
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.
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.
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; }
};
i. Default Constructor
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
implement the sum of two points such that (x1; y1) + (x2; y2)
= (x1+x2; y1+y2)
Operator Overloading Syntax
Inheritance in C++