0% found this document useful (0 votes)
12 views26 pages

C++ UNIT 1&2

The document introduces basic concepts of Object-Oriented Programming (OOP) in C++, highlighting key principles such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It explains how these concepts simplify software development and maintenance, along with practical examples of defining classes, declaring objects, and using member functions. Additionally, it covers advanced topics like static members, friend functions, and passing objects as function arguments.
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)
12 views26 pages

C++ UNIT 1&2

The document introduces basic concepts of Object-Oriented Programming (OOP) in C++, highlighting key principles such as classes, objects, inheritance, polymorphism, abstraction, and encapsulation. It explains how these concepts simplify software development and maintenance, along with practical examples of defining classes, declaring objects, and using member functions. Additionally, it covers advanced topics like static members, friend functions, and passing objects as function arguments.
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/ 26

UNIT 1

Basic Concepts of Object oriented programming


The major purpose of C++ programming is to introduce the concept of object
orientation to the C programming language.

Object Oriented Programming is a paradigm that provides many concepts such


as inheritance, data binding, polymorphism etc.

The programming paradigm where everything is represented as an object is


known as truly object-oriented programming language. Smalltalk is considered
as the first truly object-oriented programming language.

Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes
and objects. It simplifies the software development and maintenance by
providing some concepts:

o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Object

Any entity that has state and behavior is known as an object. For example:
chair, pen, table, keyboard, bike etc. It can be physical and logical.

Class

Collection of objects is called class. It is a logical entity.

A Class in C++ is the foundational element that leads to Object-Oriented


programming. A class instance must be created in order to access and use the
user-defined data type's data members and member functions. An object's class
acts as its blueprint. Take the class of cars as an example. Even if different
names and brands may be used for different cars, all of them will have some
characteristics in common, such as four wheels, a speed limit, a range of miles,
etc. In this case, the class of car is represented by the wheels, the speed
limitations, and the mileage.

Inheritance

When one object acquires all the properties and behaviours of parent
object i.e. known as inheritance. It provides code reusability. It is used to
achieve runtime polymorphism.

1. Sub class - Subclass or Derived Class refers to a class that receives


properties from another class.
2. Super class - The term "Base Class" or "Super Class" refers to the class
from which a subclass inherits its properties.
3. Reusability - As a result, when we wish to create a new class, but an
existing class already contains some of the code we need, we can
generate our new class from the old class thanks to inheritance. This
allows us to utilize the fields and methods of the pre-existing class.

Polymorphism

When one task is performed by different ways i.e. known as polymorphism.


For example: to convince the customer differently, to draw something e.g. shape
or rectangle etc.

Different situations may cause an operation to behave differently. The type of


data utilized in the operation determines the behavior.

Abstraction

Hiding internal details and showing functionality is known as abstraction.


Data abstraction is the process of exposing to the outside world only the
information that is absolutely necessary while concealing implementation or
background information.For example: phone call, we don't know the internal
processing.

In C++, we use abstract class and interface to achieve abstraction.

Encapsulation

Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
Encapsulation is typically understood as the grouping of related pieces of
information and data into a single entity. Encapsulation is the process of tying
together data and the functions that work with it in object-oriented
programming.

Dynamic Binding - In dynamic binding, a decision is made at runtime


regarding the code that will be run in response to a function call. For this, C++
supports virtual functions.

Message Passing: Objects communicate with one another by sending and


receiving information to each other. A message for an object is a request for
execution of a procedure and therefore will invoke a function in the receiving
object that generates the desired results. Message passing involves specifying

Classes and objects:


Class: A class in C++ is the building block that leads to Object-Oriented
programming. It 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 C++ class is like a blueprint for an object.
For 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
like 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.
 A Class is a user defined data-type which has data members and member
functions.
 Data members are the data variables and member functions are the functions
used to manipulate these variables and together these data members and
member functions defines 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.
An Object is an instance of a Class. When a class is defined, no memory is
allocated but when it is instantiated (i.e. an object is created) memory is
allocated.

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.
o class Student
o {
o public:
o int id; //field or data member
o float salary; //field or data member
o String name;//field or data member
o }

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:
ClassName ObjectName;

o #include <iostream>
o class Student
o {
o public:
o int id;//data member (also instance variable)
o string name;//data member(also instance variable)
o };
o int main()
o {
o Student s1; //creating an object of Student
o s1.id = 201;
o s1.name = "Esther";
o cout<<s1.id<<endl;
o cout<<s1.name<<endl;
o return 0;
o }

Defining member functions

A member function of a class is a function that has its definition or its prototype
within the class definition like any other variable. It operates on any object of
the class of which it is a member, and has access to all the members of a class
for that object.
Let us take previously defined class to access the members of the class using a
member function instead of directly accessing them −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
double getVolume(void);// Returns box volume
};
Member functions can be defined within the class definition or separately
using scope resolution operator, : −. Defining a member function within the
class definition declares the function inline, even if you do not use the inline
specifier. So either you can define Volume() function as below −
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box

double getVolume(void) {
return length * breadth * height;
}
};
If you like, you can define the same function outside the class using the scope
resolution operator (::) as follows −
double Box::getVolume(void) {
return length * breadth * height;
}
Here, only important point is that you would have to use class name just before
:: operator. A member function will be called using a dot operator (.) on a object
where it will manipulate data related to that object only as follows −
Box myBox; // Create an object

myBox.getVolume(); // Call member function for the object

Making an outside function inline

C++ inline function is powerful concept that is commonly used with classes. If
a function is inline, the compiler places a copy of the code of that function at
each point where the function is called at compile time.
Any change to an inline function could require all clients of the function to be
recompiled because compiler would need to replace all the code once again
otherwise it will continue with old functionality.
To inline a function, place the keyword inline before the function name and
define the function before any calls are made to the function. The compiler can
ignore the inline qualifier in case defined function is more than a line.
A function definition in a class definition is an inline function definition, even
without the use of the inline specifier.

o inline return_type function_name(parameters)


o {
o // function code?
o }
Example
o #include <iostream>
o inline int add(int a, int b)
o {
o return(a+b);
o }
o int main()
o {
o cout<<"Addition of 'a' and 'b' is:"<<add(2,3);A
o return 0;
o }
Advantages of inline function

o In the inline function, we do not need to call a function, so it does not


cause any overhead.
o It also saves the overhead of the return statement from a function.
o It does not require any stack on which we can push or pop the variables
as it does not perform any function calling.
o An inline function is mainly beneficial for the embedded systems as it
yields less code than a normal function.

Nesting of member functions


A member function of a class can be called only by an object of that class using
a dot operator. However, there is an exception to this. A member function can
be called by using its name inside another member function of the same class.
This is known as nesting of member functions.
Example
#include<iostream>
class add
{
public:
void get();
void display();
};
void add ::get()
{
cout<<"Enter x and y;
cin>>x>>y;
display();
}
void add ::display()
{
cout<<"z="<<z;
}
int main()
{
add ob;
ob.get();
ob.display();
return 0;
}
output:
Enter x and y
z=32765 z=32765

Private Member functions


A class can have multiple public, protected, or private labeled sections. Each
section remains in effect until either another section label or the closing right
brace of the class body is seen. The default access for members and classes is
private.
Private: The class members declared as private can be accessed only by the
member functions inside the class. They are not allowed to be accessed directly
by any object or function outside the class. Only the member functions or
the friend functions are allowed to access the private data members of the class.
Example:

#include<iostream>

using namespace std;

class Circle

// private data member

private:

double radius;

// public member function

public:

void compute_area(double r)

{ // member function can access private


// data member radius

radius = r;

double area = 3.14*radius*radius;

cout << "Radius is: " << radius << endl;

cout << "Area is: " << area;

};

int main()

Circle obj;

obj.compute_area(1.5);

return 0;

Output:
Radius is: 1.5
Area is: 7.065

Static data member


When we define the data member of a class using the static keyword, the data
members are called the static data member. A static data member is similar to
the static member function because the static data can only be accessed using
the static data member or static member function. And, all the objects of the
class share the same copy of the static member to access the static data.

Syntax
1. static data_type data_member;

Here, the static is a keyword of the predefined library.

The data_type is the variable type in C++, such as int, float, string, etc.

The data_member is the name of the static data.

Static Member Functions


The static member functions are special functions used to access the static data
members or other static member functions. A member function is defined using
the static keyword. A static member function shares the single copy of the
member function to any number of the class' objects. We can access the static
member function using the class name or class' objects. If the static member
function accesses any non-static data member or non-static member function, it
throws an error.

Syntax

1. class_name::function_name (parameter);

Here, the class_name is the name of the class.

function_name: The function name is the name of the static member function.

parameter: It defines the name of the pass arguments to the static member
function.

Example

o #include <iostream>
o class Note
o {
o // declare a static data member
o static int num;
o
o public:
o // create static member function
o static int func ()
o {
o return num;
o }
o };
o // initialize the static data member using the class name and the scope res
olution operator
o int Note :: num = 5;
o
o int main ()
o {
o // access static member function using the class name and the scope resol
ution
o cout << " The value of the num is: " << Note:: func () << endl;
o return 0;
o }

Output

The value of the num is: 5

Passing an Object as function arguments


we can pass any type of arguments within the member function and there are
any numbers of arguments.

In C++ programming language, we can also pass an object as an argument


within the member function of class.

This is useful, when we want to initialize all data members of an object with
another object, we can pass objects and assign the values of supplied object to
the current object. For complex or large projects, we need to use objects as an
argument or parameter.

Example:
#include <iostream>

class Demo {
private:
int a;

public:
void set(int x)
{
a = x;
}

void sum(Demo ob1, Demo ob2)


{
a = ob1.a + ob2.a;
}

void print()
{
cout << "Value of A : " << a << endl;
}
};

int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;

//assigning values to the data member of objects


d1.set(10);
d2.set(20);

//passing object d1 and d2


d3.sum(d1, d2);

//printing the values


d1.print();
d2.print();
d3.print();

return 0;
}

Output

Value of A : 10
Value of A : 20
Value of A : 30

Arrays of objects
 Like array of other user-defined data types, an array of type class can also
be created.
 The array of type class contains the objects of the class as its individual
elements.
 Thus, an array of a class type is also known as an array of objects.
 An array of objects is declared in the same way as an array of any built-in
data type.

Syntax:

class_name array_name [size] ;

Example:

#include <iostream>

class MyClass {
int x;
public:
void setX(int i) { x = i; }
int getX() { return x; }
};

void main()
{
MyClass obs[4];
int i;

for(i=0; i < 4; i++)


obs[i].setX(i);
for(i=0; i < 4; i++)
cout << "obs[" << i << "].getX(): " << obs[i].getX() << "\n";

getch();
}

Output:
obs[0].getX(): 0
obs[1].getX(): 1
obs[2].getX(): 2
obs[3].getX(): 3

Friend function
If a function is defined as a friend function in C++, then the protected and
private data of a class can be accessed using the function.

By using the keyword friend compiler knows the given function is a friend
function.

For accessing the data, the declaration of a friend function should be done inside
the body of a class starting with the keyword friend.

Declaration of friend function in C++

1. class class_name
2. {
3. friend data_type function_name(argument/s); // syntax of friend functi
on.
4. };

In the above declaration, the friend function is preceded by the keyword friend.
The function can be defined anywhere in the program like a normal C++
function. The function definition does not use either the keyword friend or
scope resolution operator.

Characteristics of a Friend function:


o The function is not in the scope of the class to which it has been declared
as a friend.
o It cannot be called using the object as it is not in the scope of that class.
o It can be invoked like a normal function without using the object.
o It cannot access the member names directly and has to use an object name
and dot membership operator with the member name.
o It can be declared either in the private or the public part.

 #include <iostream>
 class Box
 {
 private:
 int length;
 public:
 Box(): length(0) { }
 friend int printLength(Box); //friend function
 };
 int printLength(Box b)
 {
 b.length += 10;
 return b.length;
 }
 int main()
 {
 Box b;
 cout<<"Length of box: "<< printLength(b)<<endl;
 return 0;
 }

Output:

Length of box: 10

UNIT 2
CONSTRUCTORS AND DESTRUCTORS
Constructors
Constructors are functions of a class that are executed when new objects of the
class are created. The constructors have the same name as the class and no
return type, not even void. They are primarily useful for providing initial values
for variables of the class.
Characteristics of Constructor
A constructor is a special member function of the class. It is different from a
generic member function for the following reasons:
 Constructor member is scoped public
 It has the same name as that of declaring class.
 The name is case-sensitive
 Constructors do not have a return type.
 The default constructor is implicitly created.
 When creating an object, the constructor gets called automatically.
 A constructor is not implicitly inherited.
 It usually has different rules for scope modifiers.

The two main types of constructors are default constructors and parameterized
constructors.

Default Constructors

Default constructors do not take any parameters. If a default constructor is not


provided by the programmer explicitly, then the compiler provides a implicit
default constructor. In that case, the default values of the variables are 0.
#include <iostream>
class A
{
private:
int num1, num2 ;
public:
A()
{
num1 = 5;
num2 = 7;
}
void display()
{
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main()
{
A obj;
obj.display();
return 0;
}

Output

num1 = 5
num2 = 7

Parameterized Constructors
The parameterized constructors can take arguments to initialize an object when
it is created. Parameters are added to a parameterized constructor just like they
are added to a normal function. The parameterized constructors can be called
implicitly or explicitly.
A program that demonstrates parameterized constructors is given as follows.

Example

#include <iostream>
class A
{
private:
int num1, num2 ;
public:
A(int n1, int n2)
{
num1 = n1;
num2 = n2;
}
void display()
{
cout<<"num1 = "<< num1 <<endl;
cout<<"num2 = "<< num2 <<endl;
}
};
int main()
{
A obj(3,8);
obj.display();
return 0;
}

Output

num1 = 3
num2 = 8

Multiple constructors in a class(Constructor Overloading)


We can use the same name of the functions; whose parameter sets are different.
Here we will see how to overload the constructors of C++ classes. The
constructor overloading has few important concepts.
 Overloaded constructors must have the same name and different number
of arguments
 The constructor is called based on the number and types of the arguments
are passed.
 We have to pass the argument while creating objects, otherwise the
constructor cannot understand which constructor will be called.
 #include <iostream>
 class Rect
 {
 private:
 int area;
 public:
 Rect()
 {
 area = 0;
 }
 Rect(int a, int b)
 {
 area = a * b;
 }
 void display()
 {
 cout << "The area is: " << area << endl;
 }
 };

 main()
 {
 Rect r1;
 Rect r2(2, 6);
 r1.display();
 r2.display();
 }
 Output
 The area is: 0
 The area is: 12

Constructors with Default Arguments in C++


Default arguments of the constructor are those which are provided in the
constructor declaration.
If the values are not provided when calling the constructor the constructor uses
the default arguments automatically.
Example

#include<iostream>

using namespace std;

class Simple

int data1;

int data2;

int data3;

public:

Simple(int a, int b=9, int c=8


{

data1 = a;

data2 = b;

data3 = c;

void printData();

};

void Simple :: printData()

{
cout<<"The value of data1, data2 and data3 is "<<data1<<", "<< data2<<"
and "<< data3<<endl;

int main()

Simple s(12, 13);

s.printData();

return 0;

Copy Constructor

The copy constructor is a constructor which creates an object by initializing it


with an object of the same class, which has been created previously. The copy
constructor is used to −
 Initialize one object from another of the same type.
 Copy an object to pass it as an argument to a function.
 Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one.If
the class has pointer variables and has some dynamic memory allocations, then
it is a must to have a copy constructor.

Copy Constructor is of two types:

o Default Copy constructor: The compiler defines the default copy


constructor. If the user defines no copy constructor, compiler supplies its
constructor.
o User Defined constructor: The programmer defines the user-defined
constructor.
Syntax Of User-defined Copy Constructor:

 Class_name(const class_name &old_object);


 Consider the following situation:
 class A
 {
 A(A &x) // copy constructor.
 {
 // copyconstructor.
 }
 }

In the above case, copy constructor can be called in the following ways:

Let's see a simple example of the copy constructor.

 #include <iostream>
 class A
 {
 public:
 int x;
 A(int a) // parameterized constructor.
 {
 x=a;
 }
 A(A &i) // copy constructor
 {
 x = i.x;
 }
 };
 int main()
 {
 A a1(20); // Calling the parameterized constructor.
 A a2(a1); // Calling the copy constructor.
 cout<<a2.x;
 return 0;
 }

Output:

20

Dynamic Constructor

When you use dynamic memory allocator new inside the constructor to create
dynamic memory, it is called dynamic constructor.

By using dynamic constructor in C++, you can dynamically initialize the


objects.

1. The dynamic constructor does not create the memory of the object but it
creates the memory block that is accessed by the object.

2. You can also gives arguments in the dynamic constructor you want to
declared as shown in Example 2.

Example

#include<iostream>

class Mania

const char* ptr;


public:

// default constructor

Mania()

// allocating memory at run time

ptr = new char[15];

ptr = "Learning Mania";

void display()

cout << ptr;

};

int main()

Mania obj1;

obj1.display();

Output:

Learning Mania
Const Objects
we declare the object as constant using the const keyword in our C++
program.
By doing this, the properties of the object once initialized cannot be changed
further.If an attempt is made to change the value of any attribute of
the const object, the compiler will throw the error.

Consider the following example for instance:


#include <iostream>
using namespace std;
class Dog{
public:
string name;
string breed;
Dog(string name, string breed){
this->name = name;
this->breed = breed;
}
};
int main() {
const Dog dog("Scooby", "Breed-1");
cout << dog.name << " is of " << dog.breed << endl;

dog.breed = "Breed-2"; //Error

cout << dog.name << " is of " << dog.breed << endl;
}
If we now try to change the value of breed, the compiler will throw an error.

Destructor
Destructor is an instance member function which is invoked automatically
whenever an object is going to be destroyed. Meaning, a destructor is the last
function that is going to be called before an object is destroyed.

 Destructor is also a special member function like constructor. Destructor


destroys the class objects created by constructor.
 Destructor has the same name as their class name preceded by a tilde (~)
symbol.
 It is not possible to define more than one destructor.
 The destructor is only one way to destroy the object create by constructor.
Hence destructor can-not be overloaded.
 Destructor neither requires any argument nor returns any value.
 It is automatically called when object goes out of scope.
 Destructor release memory space occupied by the objects created by
constructor.
 In destructor, objects are destroyed in the reverse of an object creation.

 #include <iostream>
 class Employee
 {
 public:
 Employee()
 {
 cout<<"Constructor Invoked"<<endl;
 }
 ~Employee()
 {
 cout<<"Destructor Invoked"<<endl;
 }
 };
 int main(void)
 {
 Employee e1; //creating an object of Employee
 Employee e2; //creating an object of Employee
 return 0;
 }

Output:

Constructor Invoked
Constructor Invoked
Destructor Invoked
Destructor Invoked

You might also like