0% found this document useful (0 votes)
28 views

Unit 2

Class is a blueprint for creating objects with similar properties and behaviors. It defines the data members and member functions common to all objects of its type. When a class is defined, no memory is allocated but objects instantiated from the class allocate memory. Constructors initialize objects upon creation and destructors delete objects before they go out of scope. Static members are shared across all objects of a class while non-static members are unique to each object instance. Access specifiers determine whether data members and member functions are public, private, or protected.

Uploaded by

surajadine001
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Unit 2

Class is a blueprint for creating objects with similar properties and behaviors. It defines the data members and member functions common to all objects of its type. When a class is defined, no memory is allocated but objects instantiated from the class allocate memory. Constructors initialize objects upon creation and destructors delete objects before they go out of scope. Static members are shared across all objects of a class while non-static members are unique to each object instance. Access specifiers determine whether data members and member functions are public, private, or protected.

Uploaded by

surajadine001
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 36

Object Oriented Programming

(Class & 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.
C++ Objects
• 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.
• 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 objname_1, objname_2,…. Objname_n;

• Student s1, s2,…. Sn;

• Created in the main function


C++ Class Program
class student
{
int rollno; //data members named rollno and name
char name[20];
public: //access specifier
void input() //member function named input
{
cout<<"enter the rollno and name";
cin>>rollno>>name;
}
void output() //member function named output
{
cout<<rollno<<name;
}
}s1; //object can also be created this way

void main() //main function


{
student s2,s3; //objects creation
Class
• 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.
Defining a Class
• 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.
Accessing Data Members and Member Functions
• The data members and member functions of class can be accessed
using the dot(‘.’) operator with the object.
• For example if the name of object is obj and you want to access the
member function with the name printName() then you will have to
write obj.printName() .
Accessing Data Members and Member Functions
• The public data members are also accessed in the same way given
however the private data members are not allowed to be accessed
directly by the object.
• Accessing a data member depends solely on the access control of that
data member.
• This access control is given by Access modifiers in C++
• There are three access modifiers : public, private and protected.
Accessing Data Members and Member Functions
// C++ program to demonstrate accessing of data members

#include <iostream.h>
class Great
{ Output:
public: // Access specifier
string name; // Data Members The name you want to enter: Pratibha
void printname() // Member Functions()
{
cout << “The name you want to enter: " ;
cin>>name;
}
};
int main() {
Geeks obj1; // Declare an object of class Great
obj1.printname(); // accessing member function
return 0;
}
Static Data Members
• We can define class members static using static keyword.

• When we declare a member of a class as static it means no matter how many objects of the class
are created, there is only one copy of the static member.

• A static member is shared by all objects of the class.

• All static data is initialized to zero when the first object is created, if no other initialization is
present.

• We can't put it in the class definition but it can be initialized outside the class as done in the
following example by redeclaring the static variable, using the scope resolution operator :: to
identify which class it belongs to.
#include<iostream> return 0;
using namespace std; }
class student };
{ int student::rollno=0;
static int rollno;
char name[20]; int main()
public: {
int input() student s1,s2;
{ s1.input();
//cin>>rollno>>name; s1.output();
cin>>name; s2.input();
rollno++; s2.output();
return 0; s1.output();
} s2.output();
int output() return 0;
{ }
cout<<rollno<<name;
Use of static data members
● Static data members are sharable to all objects.
● Static member functions can access only static data members.
● Static data members to be declared outside the class.
● Static data functions can be accessed using classname and without object
with the help of scope resolution operator.
Static Function Members
● By declaring a function member as static, you make it independent of any particular
object of the class.

● A static member function can be called even if no objects of the class exist and the
static functions are accessed using only the class name and the scope resolution
operator (::)

● A static member function can only access static data member, other static member
functions and other member functions from outside the class.
#include<iostream> static int objectcount(){
using namespace std; cout<<"\nstudent count="<<scount;
class student
{ }
int rollno; };
char name[20]; int student::scount=0;
static int scount; int main()
public: {
int input() student s1,s2;
{ s1.input();
cin>>rollno>>name; s1.output();
scount++; student::objectcount();
return 0; s2.input();
} s2.output();
int output() student::objectcount();
{ s1.objectcount();
cout<<rollno<<name; //s1.output();
return 0; //s2.output();
} return 0;
}
Constructors
● A constructor is a member function of a class which initializes objects of a class.
● In C++, Constructor is automatically called when object(instance of class) create.
● It is special member function of the class (as it has no return type and has the same
name as the class name)

How constructors are different from a normal member function?


A constructor is different from normal functions in following ways:
● Constructor has same name as the class itself
● Constructors don’t have return type
● A constructor is automatically called when an object is created.
● If we do not specify a constructor, C++ compiler generates a default constructor for
us (expects no parameters and has an empty body).
Constructors
Syntax:
classname(parameters);

● To define a constructor outside the class


classname :: classname(parameters);

● To define a constructor inside the class


classname(parameters);
Types of Constructors
1. Default Constructors: Default constructor is the constructor which doesn’t take any
argument. It has no parameters.
ClassName (){}

ClassName (){ data=100;}

2. Parameterized Constructors: It is possible to pass arguments to constructors. Typically,


these arguments help initialize an object when it is created. To create a parameterized
constructor, simply add parameters to it the way you would to any other function. When you
define the constructor’s body, use the parameters to initialize the object.
ClassName (int data1,int data2){data1=data1,data2=data2;}
3. Copy Constructor: A copy constructor is a member function which initializes
an object using another object of the same class.
ClassName (const ClassName &old_obj)
{ data1=old_obj.data1;data2=old_obj.data2;
}
Destructors
● Destructors in C++ are members functions in a class that delete an object.
● They are called when the class object goes out of scope such as when the function ends,
the program ends, a delete variable is called etc.
● Destructors are different from normal member functions as they don’t take any
argument and don’t return anything.
● Destructors have the same name as their class and their name is preceded by a tilde(~).
● Syntax:
~classname();
#include<iostream>
int main() {
using namespace std;
Demo obj1(17, 22); //passing values in object
class Demo {
obj1.display(); //accessing function through object
private:
return 0;
int num1, num2;
public: }
Demo(int n1, int n2) { //parameterized constructor
cout<<"Inside Constructor"<<endl;
num1 = n1;
num2 = n2; Output:
} Inside Constructor
void display() { num1 = 17
cout<<"num1 = "<< num1 <<endl; num2 = 22
cout<<"num2 = "<< num2 <<endl; Inside Destructor
}
~Demo() { //destructor
cout<<"Inside Destructor";
}

};
Initializer List in C++
● Initializer List is used in initializing the data members of a class.
● The list of members to be initialized is indicated with constructor as a comma-separated
list followed by a colon.
● Works as default as well as parameterized constructor

student(int r=0, int m=100):rollno(r),marks(m){}


Sample program initializer list
#include<iostream>
int main()
#include<string.h>
{
using namespace std;
student s1;
class student
s1.output();
{
student s2(100, 105);
int rollno;
s2.output();
int marks;
return 0;
public:
}
student(int r=0, int m=100):rollno(r),marks(m){}

int output()
{
cout<<rollno<<marks;
return 0;
}
};
Const member functions
● Like member functions and member function arguments, the objects of a class can also be
declared as const.
● An object declared as const cannot be modified and hence, can invoke only const member
functions as these functions ensure not to modify the object.
● A const object can be created by prefixing the const keyword to the object declaration.
● Any attempt to change the data member of const objects results in a compile-time error.
Syntax:
const Class_Name Object_name;
Note:
*const object can call only const functions
*const objects can be initialized with initializer list
Sample program const
#include<iostream> int main()
using namespace std; {
class student const student s1;
{ s1.output();
int rollno; const student s2(100, 105);
int marks; s2.output();
public: Student s3;
student(int r=0, int m=100):rollno(r),marks(m){} return 0;
int output() const }
{
cout<<rollno<<marks;
return 0;
}
};
Inline Functions
● C++ provides an inline functions to reduce the function call overhead.
● Inline function is a function that is expanded in line when it is called.
● When the inline function is called whole code of the inline function gets inserted or
substituted at the point of inline function call.
● Substitution is performed by compiler at compile time
● An inline function may increase efficiency if it is small
● Syntax:
inline return-type function-name(parameters){

// function code

}
#include<iostream>
cin>>rollno>>name;
using namespace std;
return 0;
class student
}
{
int rollno;
int main()
char name[20];
{
public:
student s1;
int input();
s1.input();
int output()
s1.output();
{
return 0;
cout<<"\nthe roll no and name is";
}
cout<<rollno<<name;
return 0;
}
};
inline int student::input()
{
cout<<"\nenter the roll no. and name";
inline int student::input()
Array of objects {
cout<<"\nenter the roll no. and name";
cin>>rollno>>name;
#include<iostream> return 0;
using namespace std; }
class student
{ int main()
int rollno; {
char name[20]; student s[2];
public: for(int i=0;i<2;i++)
int input(); s[i].input();
int output() cout<<endl;
{ for(int i=0;i<2;i++)
cout<<"\nthe roll s[i].output();
no and name is"; return 0;
}
cout<<rollno<<name;
return 0;
}

};
Friend function in C++
● A friend function can be given special grant to access private and protected members of
a class.

● A friend function can be:


a) A method of another class
b) A global function

● 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.
/* C++ program to demonstrate the working of
// friend function definition outside the class
friend function.*/
int output(student s)
{
#include <iostream>
//accessing private data from non-member function
using namespace std;
cout<<s.rollno;
return 0;
class student
}
{
int rollno;
int main()
public:
{
int input()
student s1;
{
s1.input();
cout<<"enter the rollno";
output(s1);
cin>>rollno;
return 0;
return 0;
}
}
//friend function declaration inside the class
friend int output(student s);
};
Pointer to Object
● A pointer to a C++ class is done exactly the same way as a pointer to a structure and to access
members of a pointer to a class

● You use the member access operator -> operator, just as you do with pointers to structures.

● Also as with all pointers, you must initialize the pointer before using it.
#include<iostream> int main()
using namespace std; {
student s1,s2;
class student s1.input();
{ s2.input();
int rollno; student *s;
char name[20]; s=&s1;
public: s->output();
int input() s=&s2;
{ s->output();
cout<<"enter the rollno and name"; return 0;
cin>>rollno>>name; }
return 0;
}
int output()
{
cout<<rollno<<name;
return 0;
}
};
This Pointer
● Every object in C++ has access to its own address through an important pointer called
this pointer.

● The this pointer is an implicit parameter to all member functions. Therefore, inside a
member function, this may be used to refer to the invoking object.

When do we use this pointer?


Ans: When local variable’s name is same as member’s name
#include<iostream>
int output()
using namespace std;
{
class student
cout<<rollno<<name;
{
return 0;
int rollno;
}
char name[20];
};
public:
int input()
int main()
{
{
cout<<"enter the rollno and name";
student s1,s2;
cin>>rollno>>name;
s1.input(501);
return 0;
s2.input();
}
student *s;
//When local variable’s name is same as member’s
s=&s1;
name
s->output();
int input(int rollno)
s=&s2;
{
s->output();
this->rollno=rollno;
return 0;
return 0;
}
}
Dynamic Memory Allocation in C++
● For dynamically allocation of memory we use new and delete operator.
●We can create and delete objects at run time.
● Dynamically created objects cannot be deleted through destructors, they can be
deleted through delete operator only.
#include<iostream> ~student()
using namespace std; {
class student cout<<"\ndestructor called";
{ }
int rollno;
int marks; };
public:
student(){ int main()
rollno=1; {
marks=2; student s1(100,200);
} student s2(300,400);
student(int r,int m){ s1.output();
rollno=r; s2.output();
marks=m; student *s=new student(500,600);
} s->output();
int output(){ delete s;
student *t=new student;
cout<<endl<<rollno<<endl<<marks; t->output();
return 0; delete t;
} return 0;
}

You might also like