Oops Using C++ Notes Unit - 2
Oops Using C++ Notes Unit - 2
Class:
An object oriented programming approach is a collection of objects and each object consists of
corresponding data structures and procedures. The program is reusable and more maintainable.
The important aspect in oop is a class which has similar syntax that of structure.
class: It is a collection of data and member functions that manipulate data.The data components of class are
called data members and functions that manipulate the data are called member functions.
It can also called as blue print or prototype that defines the variables and functions common to all
objects of certain kind.It is also known as user defined data type or ADT(abstract data type)Aclass is
declared by the keyword class.
Syntax:-
class class_name
{
Access specifier:
Variable declarations;
Access specifier:
Function declarations;
};
Access Control:
Access specifier or access modifiers are the labels that specify type of access given to members of a
class. These are used for data hiding. These are also called as visibility modes. There are three types of
Access specifiers
1.private
2.public
3.protected
1. Private:
If the data members are declared as private access then they cannot be accessed from other
functions outside the class.It can only be accessed by the functions declared within the class.It is
declared by the key word „private‟.
2. public:
If the data members are declared public access then theycan be accessed from other functions out
side the class. It is declared by the key word „public‟.
3. protected:The access level of protected declaration lies between public and private.This access
specifier is used at the time of inheritance
Note:-
If no access specifier is specified then it is treated by default as private
The default access specifier of structure is public whereas that of a class is “private”
Example:
class student
{
private:int roll;
char name[30];
public:
void get_data()
{
cout<<”Enter roll number and name”:
cin>>roll>>name;
}
Void put_data()
{
cout<<”Roll number:”<<roll<<endl;
cout<<”Name :”<<name<<endl;
}
};
Object-name.function-name(actual arguments);
Ex: s.get_data();
s.put_data();
1. If the access specifier is not specified in the class the default access specifier is private
2. All member functions are to be declared as public if not they are not accessible outside the class.
Object:Instance of a class is called as object.
Syntax:
Class_name object name;
Example:
students;
in the above examples is the object.It is a real time entity that can be used
Scope Resolution operator:
Scope:-Visibility or availability of a variable in a program is called as scope.There are two
types of scope.
i)Local scope
ii)Global scope
Local scope:visibility of a variable is local to the function in which it is declared.
Global scope:visibility of a variable to all functions of a program Scope resolution operator in
“::” .
This is used to access global variables if same variables are declared as local and global
#include<iostream.h> int a=5;
Void main()
{
int a=1;
cout<<”Local a=”<<a<<endl; cout<<”Globala=”<<::a<<endl;
}
Class Scope:
Scope resolution operator (::) is used to define a function out side a class.
#include <iostream>
using namespace std;
class sample
{
public:
void output(); //function declaration
};
//function definition outside the
class void sample::output()
{
cout<<"Function defined outside the class.\n";
};
int main() { sample obj; obj.output(); return 0;
}
Output of program:
Function defined outside the class.
#include<iostream.h>
class rectangle
{
Int L,B;
public:
void get_data(); void area();
};
Void rectangle::get_data()
{
cout<<”Enter Length of rectangle”; cin>>L;
cout<<”Enter breadth of rectangle”; cin>>B;
}
int rectangle::area()
{
Return L*B;
}
int main()
{
rectangle r;
r.get_data();
cout<<”Area of rectangle is”<<r.area(); return 0;
}
INLINE FUNCTIONS:
Definition:
An inline function is a function that is expanded in line when it is invoked. Inline expansion
makesaprogramrunfasterbecausetheoverheadofafunctioncallandreturniseliminated.It is
defined by using key word “inline”
Necessity of Inline Function:
One
of the objectives of using functions in a program is to save some memory space, which becomes appreciable
when a function is likely to be called many times.
Every time
a function is called, it takes alot of extra time in executing a series of instructions for tasks such as jumping to the
function,saving registers,pushing arguments into the stack,and returning to the calling
function.
When a function is small, a substantial percentage of execution time may be spent in such overheads. One solution to
this problem is to use macro definitions,known as macros.Preprocessor macros are popular in C. The major
drawback with macros is that they are not really functions and
therefore, the usual error checking doesnot occur during compilation.
C++ has different solution to this problem.To eliminate the cost of calls to small functions,C++
Proposes a new feature called inline function.
GeneralForm:
Inline function-header
{
Function body;
Eg:
#include<iostream.h>
Inline float mul(float x,float y)
{
return (x*y);
}
Inline double div(double p,double q)
{
return (p/q);
}
int main()
{
Float a=12.345;
float b=9.82;
cout<<mul(a,b);
cout<<div(a,b);
return 0;
}
Properties of inline function:
1. Inline functions ends request but not a command to compiler
2. Compiler may serve or ignore the request
3. If function has too many lines of code or if it has complicated logic then it is executed
as normal function
Situations where inline does not work:
A function that is returning
value,if it contains switch,loop or both then it is treated as
normal function.
If a function is not returning any value and it contains are turn statement then it is treated as normal
function
If function contains static variables then
It is executed as normal function
If the inline function is declared as recursive function then it is executed as normal function.
Memory Allocation for Objects: Memory for objects is allocated when they are declared but not when
class is defined. All objects in a given class uses same member functions. The member functions are
created and placed in memory only once when they are defined in class definition
STATIC CLASS MEMBERS
Constructors
Constructors are special class functions which performs initialization of every object.
The Compiler calls the Constructor whenever an object is created. Constructors
initialize values to object members after storage is allocated to the object.
class A
{
public:
int x;
// constructor
A()
{
// object initialization
}
};
While defining a contructor you must remeber that the name of constructor will be
same as the name of the class, and contructors will never have a return type.
Constructors can be defined either inside the class definition or outside class
definition using class name and scope resolution :: operator.
class A
{
public:
int i;
A(); // constructor declared
};
// constructor definition
A::A()
{
i = 1;
}
int main()
{
Cube c;
cout << c.side;
}
10
A default constructor is so important for initialization of object members, that even if we do not define a constructor
explicitly, the compiler will provide a default constructor implicitly.
class Cube
{
public:
int side;
};
int main()
{
Cube c;
cout << c.side;
}
In this case, default constructor provided by the compiler will be called which will initialize the object data
members to default value, that will be 0 or any random integer value in this case.
2. Parameterized Constructors
These are the constructors with parameter. Using this Constructor you can provide different values to data members
of different objects, by passing the appropriate values as argument.
For example:
class Cube
{
public:
int side;
Cube(int x)
{
side=x;
}
};
int main()
{
Cube c1(10);
Cube c2(20);
Cube c3(30);
cout << c1.side;
cout << c2.side;
cout << c3.side;
}
10
20
30
By using parameterized construcor in above case, we have initialized 3 objects with user defined values. We can
have any number of parameters in a constructor.
3. Copy Constructors
These are special type of Constructors which takes an object as argument, and is used to copy values of
data members of one object into other object. Below is a sample program on Copy
Constructor:
#include<iostream>
using namespace std;
class Samplecopyconstructor
{
private:
int x, y; //data members
public:
Samplecopyconstructor(int x1, int y1)
{
x = x1;
y = y1;
}
/* Copy constructor */
Sample copy constructor (const Samplecopyconstructor &sam)
{
x = sam.x;
y = sam.y;
}
void display()
{
cout<<x<<" "<<y<<endl;
}
};
/* main function */
int main()
{
Sample copy constructor obj1(10, 15); // Normal constructor
Sample copy constructor obj2 = obj1; // Copy constructor
cout<<"Normal constructor : ";
obj1.display();
cout<<"Copy constructor : ";
obj2.display();
return 0;
}
Normal constructor : 10 15
Copy constructor : 10 15
Destructors
Destructor is a special class function which destroys the object as soon as the scope of object ends. The destructor is
called automatically by the compiler when the object goes out of scope.
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.
class A
{
public:
// defining destructor for class
~A()
{
// statement
}
};
Destructors will never have any arguments.
Example to see how Constructor and Destructor are called
Below we have a simple class A with a constructor and destructor. We will create object of the class and see when a
constructor is called and when a destructor gets called.
class A
{
// constructor
A()
{
cout << "Constructor called";
}
// destructor
~A()
{
cout << "Destructor called";
}
};
int main()
{
A obj1; // Constructor Called
int x = 1
if(x)
{
A obj2; // Constructor Called
} // Destructor Called for obj2
} // Destructor called for obj1
Constructor called
Constructor called
Destructor called
Destructor called
When an object is created the constructor of that class is called. The object reference is destroyed when its scope
ends, which is generally after the closing curly bracket } for the code block in which it is created.
The object obj2 is destroyed when the if block ends because it was created inside the if block. And the
object obj1 is destroyed when the main() function ends.
Single Definition for both Default and Parameterized Constructor
In this example we will use default argument to have a single definition for both defualt and parameterized
constructor.
class Dual
{
public:
int a;
Dual(int x=0)
{
a = x;
}
};
int main()
{
Dual obj1;
Dual obj2(10);
}
Here, in this program, a single Constructor definition will take care for both these object initializations. We don't
need separate default and parameterized constructors.
Member Function
A member function in C++ is a function that is part of a class. It is used to manipulate the data
members of the class. Member functions are also known as methods. Member functions are declared
inside the class definition and can be defined either inside or outside the class definition. A function
declared as a member of the class is called a member function. Generally, member functions are
declared as public because they have to be called outside of the class. Member functions are very
useful to achieve OOPs concept encapsulation which is used to access private data members of the
class using public member functions. In this article, we will learn about member function in-depth,
ways to define member function, and types of member function
Member Function
A function is a Member Function if it can be declared as a member of the class (Function declaration or definition
within the class). Member Functions can be declared within the class as public, private, or protected functions.
Member Functions may be used to read, manipulate, or display all types of data members (private, public, and
protected). Member Function is declared as any other variable in C++.
employee_tech = tech;
}
void setSalary(double salary){
employee_salary = salary;
}
int getId(){
return employee_id;
}
string getName(){
return empoyee_name;
}
string getTech(){
return employee_tech;
}
double getSalary(){
return employee_salary;
}
}
In the above example we have defined the function setId (definition = employee_id=id ). We have defined other
functions like setName, setTech, setSalary, getName, getId, etc. We can create an object of class Employee and we
can use above defined functions to set values of the private variable (ex:- id, name, tech, salary). We can also use
the defined function to get the values of the private variables. The problem with this method is when we write long
definitions it’s become more complex to read the code.
Defining Member Function outside the Class
In this method, we can declare a function within the class and we define the function outside the class to achieve the
Member Function in C++. While using this method we need to ensure that the function is declared within the class.
The problem with this method is when we have more than one class having the same function name so it will be
confusing which function’s definition it is.
Below is a small example given to understand the problem?
class Circle{
int size;
public:
void printSize(int s);
}
class Square{
int size;
public:
void printSize(int s);
}
We can see that there is the same function [ printSize( int s ) ] in both classes ( Circle, Square ). To avoid this
problem we can use the scope resolution operator (::). The syntax of using the scope resolution operator to achieve
Member Function in C++ is given below.
return_type class_name :: member_function_name (arguments){
// definition of the function
}
Let’s see how we can define the member function of both classes ( Circle, Square ) using the scope resolution
operator and the above syntax.
# include <iostream>
using namespace std;
class Employee{
int employee_id;
string employee_name;
string employee_tech;
double employee_salary;
public:
// only declaration of the functions
void setId(int id);
void setName(string name);
void setTech(string tech);
void setSalary(double salary);
int getId();
string getName();
string getTech();
double getSalary();
}
// definition of the functions outside the class
void Employee :: setId(int id){
employee_id=id;
}
void Employee :: setName(int name){
employee_name=name;
}
void Employee :: setTech(int tech){
employee_tech=tech;
}
void Employee :: setSalary(int salary){
employee_salary=salary;
}
int Employee :: getId(){
return employee_id;
}
string Employee :: getName(){
return employee_name;
}
string Employee :: getTech(){
return employee_tech;
}
double Employee :: getSalary(){
return employee_salary;
}
}
In the above example, we can see that we have only declared the member functions [ex:- getId(), setId(), etc. ] in the
class itself and we define the function outside the class Employee using the scope resolution operator. This method
of defining the Member Function in C++ is generally used when the definition of the function is large. This method
is very efficient and readable.
Types of Member Function in C++
There are five types of Member Function in C++.
Simple Function
Const Function
Static Function
Inline Function
Friend Function
1. Simple Function
Simple Functions are declared without using any specific keyword ( ex:- static, const ). Simple Functions do not
have any specific behavior.
#include <iostream>
using namespace std;
class Shape{
public:
// Simple Member Function
int square(int length){
return length*length;
}
}
</iostream>
2. Const Function
Constant Functions are functions that are not able to modify data members of the class. We can declare Const
Function using the const keyword at the end of the arguments parenthesis. The syntax of the Const Function is
given below.
Syntax :-
return_type function_name ( arguments ) **const ;**
#include <iostream>
using namespace std;
class Shape{
int length;
public:
Shape(int len=0){
length=len; // data member can be assigned only once
}
// Const Member Function
int square(int len) const{
// length=10; if we uncomment this line code will throw an error because we can't modify the data member
return length*length;
}
};
3. Static Function
Static Functions are created using static keyword before the return type of function declaration. Static Functions can
only call static members and static functions inside the static function definition because Static members functions
do not have implicit this argument. We can direct call Static Functions without creating an object of the class. Using
the scope resolution operator (::) we can call the static function directly.
#include <iostream>
using namespace std;
class Shape{
Public:
// Static Function
static int square(int length){
return length*length;
}
};
int main(){
// call Static Function without creating an object of class
std::cout << Shape::square(10) << std::endl;
return 0;
}
4. Inline Function
Inline Functions are created using the inline keyword before the return type of the function declaration. Inline
Functions are used to reduce overhead function calling. Inline Function may increase efficiency of the code if it has
a small definition.
#include <iostream>
using namespace std;
inline int square(int length){
return length*length;
}
int main(){
std::cout << square(10) << std::endl;
return 0;
}
5. Friend Function
Friends Functions are functions that have their definition outside (non-member function) of the class but they can
still access private and protected members of the class. To access private and protected members outside the class
definition of the Friend Function should be inside the class. Friend Functions are declared inside the class using
a friend keyword before the return type of the function.
#include <iostream>
using namespace std;
class Shape{
int length; // private member of the class
public:
// friend function declaration
friend int square(int len);
};
// definition of friend function
int square(int len){
Shape s;
s.length=len; // access private variable
return s.length*s.length;
}
int main(){
std::cout << square(10) << std::endl;
return 0;
}
1 #include <iostream>
2
3 using namespace std;
4 void Test(){
5
6 static int x = 1;
7 x = ++x;
8
9 int y = 1;
10 y = ++y;
11 cout<<"x = "<<x<<"n";
12 cout<<"y = "<<y<<"n";
13 }
14 int main()
15 {
16 Test();
17 Test();
18
19 return 0;
20 }
Output:
From the above output, we can conclude that every time the Test( ) function was called a copy of variable ‘y’ was created while the
same copy of variable ‘x’ was used every time the Test( ) function was called.
2. Throughout the program, only one copy of the static member variable is created for the entire class hence static member
variables are also called class variables. It is shared by all instances of the class.
3. The static member variable is only visible within the class but its lifetime is till the program ends.
Creating References
A reference variable is a "reference" to an existing variable, and it is created with the & operator:
string food = "Pizza"; // food variable
string &meal = food; // reference to food
Now, we can use either the variable name food or the reference name meal to refer to the food variable:
Example
string food = "Pizza";
string &meal = food;
cout << food << "\n"; // Outputs Pizza
cout << meal << "\n"; // Outputs Pizza
NEW OPERATOR
The new operator requests for the memory allocation in heap. If the sufficient memory is available, it initializes the
memory to the pointer variable and returns its address.
Here is the syntax of new operator in C++ language,
pointer_variable = new datatype;
Here is the syntax to initialize the memory,
pointer_variable = new datatype(value);
Here is the syntax to allocate a block of memory,
pointer_variable = new datatype[size];
Here is an example of new operator in C++ language,
Example
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(223.324);
int *ptr3 = new int[28];
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
if (!ptr3)
cout << "Allocation of memory failed\n";
else {
for (int i = 10; i < 15; i++)
ptr3[i] = i+1;
cout << "Value of store in block of memory: ";
for (int i = 10; i < 15; i++)
cout << ptr3[i] << " ";
}
return 0;
}
Output
Value of pointer variable 1 : 28
Value of pointer variable 2 : 223.324
Value of store in block of memory: 11 12 13 14 15
DELETE OPERATOR
The delete operator is used to deallocate the memory. User has privilege to deallocate the created pointer
variable by this delete operator.
Here is the syntax of delete operator in C++ language,
delete pointer_variable;
Here is the syntax to delete the block of allocated memory,
delete[ ] pointer_variable;
Here is an example of delete operator in C++ language,
Example
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int[28];
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
if (!ptr3)
cout << "Allocation of memory failed\n";
else {
for (int i = 10; i < 15; i++)
ptr3[i] = i+1;
cout << "Value of store in block of memory: ";
for (int i = 10; i < 15; i++)
cout << ptr3[i] << " ";
}
delete ptr1;
delete ptr2;
delete[] ptr3;
return 0;
}
Output
Value of pointer variable 1 : 28
Value of pointer variable 2 : 299.121
Value of store in block of memory: 11 12 13 14 15
Assignment Operators
In C++, the assignment operator forms the backbone of many algorithms and computational processes by performing a simple
operation like assigning a value to a variable. It is denoted by equal sign ( = ) and provides one of the most basic operations in
any programming language that is used to assign some value to the variables in C++ or in other words, it is used to store some
kind of information.
Syntax
variable = value;
The right-hand side value will be assigned to the variable on the left-hand side. The variable and the value should be of the
same data type.
The value can be a literal or another variable of the same data type.
Example
C++
// C++ program to illustrate the use of assignment operator
#include <iostream>
using namespace std;
int main()
{
// Declare an integer variable
int x;
// Assign the value 20 to variable x using assignment
// operator
x = 20;
cout << "The value of x is: " << x << endl;
return 0;
}
Output
The value of x is: 20
Compound Assignment Operators
In C++, the assignment operator can be combined into a single operator with some other operators to perform a combination
of two operations in one single statement. These operators are called Compound Assignment Operators. There are 10
compound assignment operators in C++:
1. Addition Assignment Operator ( += )
2. Subtraction Assignment Operator ( -= )
3. Multiplication Assignment Operator ( *= )
4. Division Assignment Operator ( /= )
5. Modulus Assignment Operator ( %= )
6. Bitwise AND Assignment Operator ( &= )
7. Bitwise OR Assignment Operator ( |= )
8. Bitwise XOR Assignment Operator ( ^= )
9. Left Shift Assignment Operator ( <<= )
10. Right Shift Assignment Operator ( >>= )
1. Addition Assignment Operator (+=)
In C++, the addition assignment operator (+=) combines the addition operation with the variable assignment allowing you to
increment the value of variable by a specified expression in a concise and efficient way.
Syntax
variable += value;
This above expression is equivalent to the expression:
variable = variable + value;
Example
C++
// C++ program to illustrate the addition assignment operator
#include <iostream>
using namespace std;
int main()
{
// Initialize a variable to the store the total
int total = 0;
total += 10;
total += 20;
total += 30;
total += 40;
total += 50;
// Display the final total
cout << "The total is: " << total << endl;
return 0;
}
Output
The total is: 150
2. Subtraction Assignment Operator (-=)
The subtraction assignment operator (-=) in C++ enables you to update the value of the variable by subtracting another value
from it. This operator is especially useful when you need to perform subtraction and store the result back in the same
variable.
Syntax
variable -= value;
This above expression is equivalent to the expression:
variable = variable - value;
Example
C++
// C++ program to illustrate the substraction assignment
#include <iostream>
using namespace std;
int main()
{
int x = 20;
int y = 5;
// Using the subtraction assignment operator
x -= y;
cout << "After subtraction x is now: " << x << endl;
return 0;
}
Output
After subtraction x is now: 15
3. Multiplication Assignment Operator (*=)
In C++, the multiplication assignment operator (*=) is used to update the value of the variable by multiplying it with another
value.
Syntax
variable *= value;
This above expression is equivalent to the expression:
variable = variable * value;
Example
C++
#include <iostream>
using namespace std;
int main() {
int x = 7; // Initialize x to 7
x *= 4;
cout << "The updated value of x is: " << x << endl;
return 0;
}
Output
The updated value of x is: 28
4. Division Assignment Operator (/=)
The division assignment operator divides the variable on the left by the value on the right and assigns the result to the variable
on the left.
Syntax
variable /= value;
This above expression is equivalent to the expression:
variable = variable / value;
Example
C++
// C++ program to illustrate the use of divide assignment
#include <iostream>
using namespace std;
// driver code
int main()
{
double x = 30.0;
// dividing x by 4 and assigning the value to x
x /= 4.0;
cout << "value : " << x << endl;
return 0;
}
Output
value : 7.5
5. Modulus Assignment Operator (%=)
The modulus assignment operator calculates the remainder when the variable on the left is divided by the value or variable on
the right and assigns the result to the variable on the left.
Syntax
variable %= value;
This above expression is equivalent to the expression:
variable = variable % value;
Example
C++
// C++ program to illustrate the use of modulus assignment
#include <iostream>
using namespace std;
int main()
{
int a = 15;
// finding the remainder when a is divided by 15 and
// assigning it to a again
a %= 5;
cout << "value : " << a << endl;
return 0;
}
Output
value : 0
6. Bitwise AND Assignment Operator (&=)
This operator performs a bitwise AND between the variable on the left and the value on the right and assigns the result to the
variable on the left.
Syntax
variable &= value;
This above expression is equivalent to the expression:
variable = variable & value;
Example
C++
// C++ program to illustrate the use of Bitwise AND
#include <iostream>
using namespace std;
int main()
{
int a = 9;
// using Bitwise AND Assignment Operator
a &= 3;
cout << "value : " << a << endl;
return 0;
}
Output
value : 1
Output
value : 7
Output
value : 4
Output
value : 144
Output
value : 1
Also, it is important to note that all of the above operators can be overloaded for custom operations with user-defined data
types to perform the operations we want.