0% found this document useful (0 votes)
14 views150 pages

Unit-I Oop RBK

The document provides an overview of Object-Oriented Programming (OOP) and contrasts it with Procedural Oriented Programming (POP), highlighting key concepts such as encapsulation, inheritance, polymorphism, and data abstraction. It explains the structure of C++ programs, variable declaration, and the use of constants, along with examples of basic programming constructs. Additionally, it covers data types in C++, including primitive, derived, and user-defined types.

Uploaded by

jay thorat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views150 pages

Unit-I Oop RBK

The document provides an overview of Object-Oriented Programming (OOP) and contrasts it with Procedural Oriented Programming (POP), highlighting key concepts such as encapsulation, inheritance, polymorphism, and data abstraction. It explains the structure of C++ programs, variable declaration, and the use of constants, along with examples of basic programming constructs. Additionally, it covers data types in C++, including primitive, derived, and user-defined types.

Uploaded by

jay thorat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 150

UNIT I

Foundations of OOP
Procedural Oriented Programming
Language
• Conventional programming, using high-level
language such as COBOL, FORTRAN and C are
commonly known as Procedure Oriented
Programming (POP) languages.

• In POP, number of functions are written to


accomplish the tasks
Procedural Oriented Programming
- Structure -
Main
program

Function-1 Function-2 Function-3

Function-4 Function-5

Function-6 Function-7 Function-8


Procedure Oriented Language
- Characteristics -

• Emphasis (importance) is on doing things


(algorithms).
• Larger programs are divided into smaller programs
known as functions.
• Most of the functions share global data.
• Data move openly around the system from
function to function.
• Employs top-down approach in program design.
Procedural Oriented Language
- Limitations -
• Data move freely around the program and are
therefore vulnerable to changes caused by any
function in the program.
• It does not model very well to the real world
problems.
Object Oriented Programming
• OOP treats data as a critical element
• Ties data more closely to the functions that
operate on it & allows decomposition of
problem into objects.
OBJECT

Operations

Data

OBJECT OBJECT

Operations Operations

Data Communication Data


Procedure Oriented Programming Object Oriented Programming
In POP, program is divided into small parts In OOP, program is divided into parts
Divided Into
called functions called objects

In POP, Importance is not given to data but to In OOP, Importance is given to the data rather than
Importance functions as well as sequence of actions to be procedures or functions because it works as a real
done world

Approach POP follows Top Down approach OOP follows Bottom Up approach

OOP has access specifiers named Public, Private,


Access Specifiers POP does not have any access specifier.
Protected, etc.

In POP, Data can move freely from function to In OOP, objects can move and communicate with
Data Moving
function in the system each other through member functions

To add new data and function in POP is not so OOP provides an easy way to add new data and
Expansion
easy function

In POP, Most function uses Global data for In OOP, data can not move easily from function to
Data Access sharing that can be accessed freely from function function, it can be kept public or private so we can
to function in the system control the access of data

POP does not have any proper way for hiding OOP provides Data Hiding so provides more
Data Hiding
data so it is less secure security

Examples Example of POP are : C, VB, FORTRAN, Pascal Example of OOP are : C++, JAVA, VB.NET, C#.NET
Fundamentals of OOP
• Objects
• Classes
• Encapsulation
• Data Abstraction
• Inheritance
• Polymorphism
• Dynamic Binding
• Message Passing
//Program: Basic Program

#include <iostream>
using namespace std;

int main() {
cout << "Hello World!";
return 0;
}

Output: Hello World!


Structure of C++ Program

Include Files

Class Definition

Class Function Definition

Main Function Program


Simple C++ Program
// Hello World program comment

#include <iostream.h> Allows access to an I/O


library

int main() { Starts definition of special function


main()

cout << "Hello World\n"; output (print) a


string

return 0; Program returns a status


} code (0 means OK)
• The std is a short form of standard, the std
namespace contains the built-in classes and
declared functions. You can find all the standard
types and functions in the C++ "std" namespace

• If you do not write using namespace std , then


you need to fully qualify the names you use
from the standard library. That means std::string
instead of string , std::cout instead of cout
>> :- Input using Extraction operator
C++

Output using insertion


operator
Objects
• OOP uses objects as its fundamental building
blocks.
• Objects are the basic run-time entities in an
object-oriented system.
• Every object is associated with data and
functions which define meaningful operations
on that object.
• Object is a real world existing entity.
• Object is an Instance of a particular class.
//Program: Create a Car class with some attributes

#include <iostream>
#include <string>
using namespace std; int main() {
Car carObj1;
carObj1.brand = "BMW";
class Car { carObj1.model = "X5";
public: carObj1.year = 1999;
string brand;
string model; Car carObj2;
int year; carObj2.brand = "Ford";
carObj2.model = "Mustang";
};
carObj2.year = 1969;
cout << carObj1.brand << " " << carObj1.model << " " <<
carObj1.year << "\n";
cout << carObj2.brand << " " << carObj2.model << " " <<
carObj2.year << "\n";
return 0;
}

Output:
BMW X5 1999
Ford Mustang 1969
Object

Operation

Operation Attributes Operation

Operation
Example: StudentObject

Enroll()

st_name
st_id Displayinfo()
Performance()
branch
semester

Result()
Class
• Class is a collection of objects.

Class
Encapsulation
• The wrapping up of data and functions into a
single unit (called class) is known as
encapsulation.

• It is a mechanism that associates the code and


the data & it manipulates into a single unit
and keeps them safe from external
interference and misuse.
Encapsulation
#include <iostream>
using namespace std;
class Employee { int main()
private: {
int salary; Employee myObj;
myObj.setSalary(50000);
public:
cout << myObj.getSalary();
void setSalary(int s)
return 0;
{ }
salary = s;
} Output: 50000
int getSalary()
{
return salary;
}
Data Abstraction
• Abstraction refers to the act of representing
essential features without including the
background details or explanations.

• A data abstraction is a simplified view of an object


that includes only features one is interested in
while hides away the unnecessary details.
Inheritance
• Inheritance is the mechanism to provides the
power of reusability and extendibility.

• Inheritance is the process by which one object


can acquire the properties of another object.
Inheritance

Parent class
Or
Base class
Point

Child class
Or
Derived
class
Line
Polymorphism
• The ability to take more than one form.

• Polymorphism means that the same thing can


exist in more than one forms.

• Polymorphism is in short the ability to call


different functions by just using one type of
function call.
Polymorphism
5+9 Str + ing

+
Dynamic Binding
• Dynamic Binding is the process of linking of
the code associated with a procedure call at
the run-time
Message Passing
• The process of invoking an operation on an
object.
• In response to a message the corresponding
method is executed in the object
Message Passing
StudentObject FacultyObject

Performance

MgmtObject Performance
Result
Variable Declaration
• A variable defines a location in the memory that
holds a value which can be modified later.
• Syntax:
type variable_list;
• In the above syntax "type" refers to any one of the
C++ data types.
Declaring Variables
• Variables in C++ should be declared before they are used in the
code block.
#include <iostream.h>
void main()
{
int n = 10;
cout << "Integer value is:"<< n << '\n';
}

• Result:
Integer value is: 10
In the above example "n" is an integer variable declared
using return type "int".
Rules for Naming variables in C++
• Always the first character of a variable must be a
letter or an underscore.
• The variable name cannot start with a digit.
• Other characters should be either letters, digits,
underscores.
• There is no limit for the length of variables.
• Declared keywords cannot be used as a variable
name.
• Upper and lower case letters are distinct.
Variable Scope
• A scope is a region of the program and broadly
speaking there are three places, where
variables can be declared:
– Inside a function or a block which is called local
variables,
– In the definition of function parameters which is
called formal parameters
– Outside of all functions which is called global
variables.
Local variables
• Parameters and variables declared inside the
definition of a function are local.
• They only exist inside the function body.
• Once the function returns, the variables no
longer exist!
Example Using Local Variables:
#include <iostream.h>
int main ()
{ // Local variable declaration:
int a, b;
int c;
// actual initialization
a = 10;
b = 20;
c = a + b;
cout << c;
return 0;
}
Global Variables
• We can declare variables outside of any
function definition – these variables are
global variables.
• Any function can access/change global
variables.
• Example: flag that indicates whether
debugging information should be printed.
Example Using Global and Local Variables
#include <iostream>
// Global variable declaration:
int g;
int main ()
{ // Local variable declaration:
int a, b;
// actual initialization
a = 10;
b = 20;
g = a + b;
cout << g;
return 0;
}
Constants (const)
• Constants refer to fixed values that the
program may not alter
• Defining Constants:
• Using #define preprocessor.
• Using const keyword.
The #define Preprocessor:
• Following is the form to use #define preprocessor to define a
constant:
#define identifier value
Example
#include <iostream>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main()
{ int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0;
Result: 50
}
The const Keyword:
• use const prefix to declare constants with a specific type as follows:
const type variable = value;
Example:-
#include <iostream.h>
int main()
{
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
cout << area;
cout << NEWLINE;
return 0; Output:50
}
Reference Variable
• Variable name as a label attached to the
variable's location in memory.
• Reference as a second label attached to that
memory location.
• Access the contents of the variable through
either the original variable name or the
reference.
• Syntax:
Data-type & reference name = variable name
• For example
int i = 17;
• We can declare reference variables for i as follows.
int& r = i;
the & in this declaration is as reference.
• Read declaration as "r is an integer reference
initialized to i"
Example
#include <iostream>
int main ()
{
// declare simple variables
int i; double d; Output:
// declare reference variables Value of i : 5
int& r = i; Value of i reference : 5
double& s = d; Value of d : 11.7
Value of d reference : 11.7
i = 5;
cout << "Value of i : " << i << endl;
cout << "Value of i reference : " << r << endl;
d = 11.7;
cout << "Value of d : " << d << endl;
cout << "Value of d reference : " << s << endl;
return 0;
}
Comments in C++
• Program comments are explanatory
statements that you can include in the C++
code that you write and helps anyone reading
it's source code.
• C++ supports single-line and multi-line
comments. All characters available inside any
comment are ignored by C++ compiler.
• C++ comments start with /* and end with */.
For example:
/* This is a comment */
/* C++ comments can also
* span multiple lines
*/
• A comment can also start with //, extending to the
end of the line.
• For example:
#include <iostream.h>
main()
{
cout << "Hello World"; // prints Hello World
return 0;
}
Output : Hello World
Default Parameter
• C++ allows to call function without specifying all
its arguments
• In such cases, the function assigns default value
to the parameter which does not have a matching
argument in the function call.
• Default values are specified when function is
declared.
• The compiler looks at the prototype to see how
many arguments a function uses and alerts the
program for possible default values.
• The default value is specified in a manner
syntactically similar to a variable initialization.
• Add default values from right to left.
• Cannot provide a default value in the middle
of an argument list.
Default parameter (Example)
float amount(float principal, float period, float rate=0.15);
Default value 0.15 to parameter rate
Function call like
value = amount (5000,7); //one parameter missing
Passes 0.15 to rate

Now,
value =amount(5000,7,0.12) //no missing argument
Passes explicit value 0.12 to rate
#include<iostream.h> Output:
#include<conio.h> Enter Length:6
int vol(int=1,int=2,int=3); Enter width:5
main() { Enter height: 9
clrscr(); Volume with no argument passed =6
int length; int width; int height; Volume with one argument passed=36
int volume;
cout<<"\n Enter length = ";
cin>>length;
cout<<"\n Enter width = "; int vol(int l,int h,int w)
cin>>width; {
cout<<"\n Enter heigth = "; return l*h*w;
cin>>height; }
volume=vol();
cout<<"\n Volume with no argument passed ="<<volume;
volume=vol(length);
cout<<"\n Volume with one argument passed = "<<volume;
volume=vol(length,width);
getch();
return 0; }
Data Types
C++ supports the following data types:

• Primary or Built-in or Fundamental data type


• Derived data types
• User-defined data types
Data Types
Data Types
Data Types in C++ are Mainly Divided into 3 Types:
1. Primitive Data Types: These data types are built-in or predefined
data types and can be used directly by the user to declare variables.
example: int, char, float, bool, etc. Primitive data types available in C+
+ are:

• Integer
• Character
• Boolean
• Floating Point
• Double Floating Point
• Valueless or Void
• Wide Character
Data Types
2. Derived Data Types: Derived data types that are
derived from the primitive or built-in datatypes are
referred to as Derived Data Types. These can be of
four types namely:

• Function
• Array
• Pointer
• Reference
Data Types
3. Abstract or User-Defined Data Types: Abstract or
User-Defined data types are defined by the user itself.
Like, defining a class in C++ or a structure. C++
provides the following user-defined datatypes:

• Class
• Structure
• Union
• Enumeration
• Typedef defined Datatype
Datatype Modifiers
Datatype Modifiers
Data type modifiers available in C++ are:

• Signed
• Unsigned
• Short
• Long
Datatype Modifiers
Data Type Size (in bytes) Range

short int 2 -32,768 to 32,767

unsigned short int 2 0 to 65,535

unsigned int 4 0 to 4,294,967,295

-2,147,483,648 to
int 4
2,147,483,647

-2,147,483,648 to
long int 4
2,147,483,647

unsigned long int 4 0 to 4,294,967,295


Datatype Modifiers
Data Type Size (in bytes) Range

long long int 8 -(2^63) to (2^63)-1

0 to
unsigned long long int 8
18,446,744,073,709,551,615

signed char 1 -128 to 127

unsigned char 1 0 to 255

float 4 -3.4×10^38 to 3.4×10^38

double 8 -1.7×10^308 to1.7×10^308


Datatype Modifiers

Data Type Size (in bytes) Range


long double 12 -1.1×10^4932 to1.1×10^4932
wchar_t 2 or 4 1 wide character
/ C++ program to Demonstrate the sizes of data types

#include <iostream>
#include <limits.h>
using namespace std;

int main()
{
cout << "Size of char : " << sizeof(char) << " byte" << endl;

cout << "char minimum value: " << CHAR_MIN << endl;

cout << "char maximum value: " << CHAR_MAX << endl;

cout << "Size of int : " << sizeof(int) << " bytes"<< endl;

cout << "Size of short int : " << sizeof(short int) << " bytes" << endl;
cout << "Size of signed long int : "
<< sizeof(signed long int) << " bytes" << endl;

cout << "Size of unsigned long int : “ << sizeof(unsigned long int)
<< " bytes" << endl;

cout << "Size of float : " << sizeof(float) << " bytes“ << endl;

cout << "Size of double : " << sizeof(double) << " bytes" << endl;

cout << "Size of wchar_t : " << sizeof(wchar_t) << " bytes" <<
endl;

return 0;
Output:

Size of char : 1 byte


char minimum value: -128
char maximum value: 127
Size of int : 4 bytes
Size of short int : 2 bytes
Size of long int : 8 bytes
Size of signed long int : 8 bytes
Size of unsigned long int : 8 bytes
Size of float : 4 bytes
Size of double : 8 bytes
Size of wchar_t : 4 bytes
C++ Functions
• Set of program statements that can be
processed independently.

• Like in other languages, called subroutines or


procedures.
Advantages …?
• Elimination of redundant code
• Easier debugging
• Reduction in the Size of the code
• Leads to reusability of the code
• Achievement of Procedure Abstraction
Function Prototype
• Is a declaration statement in program
• Syntax:
Return type function name (parameter list);
Sample function

n n ame Formal parameters


Return type F io
unct

int add_int(int a, int b)


{
return(a+b);
} Fu n
ctio
n bo d
y
Function Overloading
• Overloading refers to the use of the same
thing for different purposes.
• Multiple functions to share the same name
with different signatures(types or numbers).

int myfunc(int i) int myfunc(int i, int j)


{ {
return i; return i*j;
} }
Inline Functions
• Disadvantages of using function
 Every time a function is called, it take a lot of extra
time in executing a series of instructions.
 In the following ways of execution it takes more
time
 Jumping to the function
 Saving in Register.
 Pushing arguments into the stack.
 Returning to the calling function.
Inline Functions
• To eliminate the cost of calls to small functions, c++ provides a
new feature called inline function.
• Inline functions are those whose function body is inserted in
place of the function call statement during the compilation
process.

• Syntax:
inline return_type func_name(formal parameters)
{
function body
}
Inline Functions
• Situations where inline expansion not work /
conditions for inline function:
– Function should not have any return statement, if
a loop, a switch, or a goto exists
– Function should not be recursive
– Function length should be small
– Function should not contain static variable
Example
void main()
#include<iostream.h>
{
#include<conio.h>
line obj;
float val1,val2;
class line
clrscr();
{
cout<<"Enter two values:";
public:
cin>>val1>>val2;
inline float mul(float x,float y)
cout<<"\nMultiplication value is:“;
{
cout<<obj.mul(val1,val2);
return(x*y);
cout<<"\n\nCube value is:”;
}
cout<<obj.cube(val1)<<"\
inline float cube(float x)
t"<<obj.cube(val2);
{
getch();
cout<<(x*x*x);
}
}
};
Inline Function
• Advantages
Shorter execution time
Does not require function calling overhead
Saves time
Memory Management Operator
• C++ supports two unary operators new and delete
operators that perform the task of allocating and
freeing the memory in a better and easier way.
• These operators manipulate memory on the free
store, they are also known as free store operators.
• Objects can be created by using new and deleted
by using delete operator.
• Syntax:
Pointer variable = new data-type
Pointer
• A pointer is a variable that stores the memory
address as its value.

• A pointer variable points to a data type (like int


or string) of the same type, and is created with
the * operator.
• The address of the variable is assigned to the
pointer:
//Program for pointer
#include <iostream>
#include <string>
using namespace std;
int main() {
string food = "Pizza"; // A string variable
string* ptr = &food; // A pointer variable that stores the address of food

cout << food << "\n"; // Output the value of food

cout << &food << "\n"; // Output the memory address of food

cout << ptr << "\n"; // Output the memory address of food with the pointer
return 0;
}
Output:

Pizza
0x6dfed4
0x6dfed4
Example
Int *p=new int;
Float *q=new float;
• Suppose
*p=25
*q=7.5
• int* p = new int(25);
• float* q = new float(75.25);
• pointer-variable = new data-type(value);
Example
• pointer-variable = new data-type[size];
• a new operator is also used to allocate a
block(an array) of memory of type data type.

Example:
• int *p = new int[10]
• Data object no longer needed, it is destroyed
to release memory space for reuse.
• Syntax
delete pointer variable

Example :
delete q;
delete p;
Example:

// It will free the entire array


// pointed by p.
delete[] p;
Scope Resolution Operator

• Inner block hides a declaration of the same


variable in an outer block.
• :: scope resolution operator to uncover a
hidden variable.
• Syntax : : variable_name
• This operator allows access to the global
version of a variable.
Manipulators
• Manipulators are operators that are used to
format the data display.
1) endl : It causes a linefeed to be inserted.
2) setw(int w) : Specifies a field width and right
alignment. Set the field width to w.
3) setprecision(int d) : To specify number of
digits after decimal point. Set the floating
point precision to d.
4) setbase(int d): It is used to set the base value
of a numerical number.
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
float PI = 3.14;
int num = 100;
cout << "Entering a new line." << endl;
cout << setw(10) << "Output" << endl;
cout << setprecision(10) << PI << endl;
cout << setbase(16) << num << endl; //sets base to 16
}
Output:
Entering a new line.
3.140000105
64
Defining Class
Class Specification
• Syntax:
class class_name
{
Data members

Members functions

};
Class Specification
• class Student
{
int st_id; Data Members or Properties of
char st_name[]; Student Class

void read_data(); Members Functions or


void print_data(); Behaviours of Student Class

};
Class Specification
• Visibility of Data members & Member functions

Public –
Accessed by member functions and all other non-member
functions in the program.
Private –
Accessed by only member functions of the class.
Protected –
Similar to private, but accessed by all the member functions of
immediate derived class
Default –
All items defined in the class are private.
Class Specification
• class Student
{
int st_id;
char st_name[]; private / default
void read_data(); visibility
void print_data();
};
Class Specification
• class Student
{
public:
int st_id;
char st_name[]; public visibility
public:
void read_data();
void print_data();
};
Class Specification
class MyClass { // The class
public: // Access specifier
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Class Objects
• Object Instantiation:
The process of creating object of the type class
• Syntax:
class_name obj_name;
e o b j ect of the
singl
ex: Student st; Creat es a
tudent!
type S

St_id, St_name

void read_data( )

void print_data( )
Class Object
• More of Objects
ex: Student st1;
Student st2;
Student st3;
Class Objects
10,Rama 20, Stephen

void read_data( ) void read_data( )

void print_data( ) void print_data( )

st1 st2
55, Mary

void read_data( )

void print_data( )

st3
Accessing Data Members
(inside the class)
• Syntax: (single object)
data_member;
ex: st_id;
Accessing Data & Members Functions
(outside the class)
• Using dot (.) operator
• Syntax: (single object)

obj_name . datamember;
obj_name . Member_function(actual param)
e.g. : st.st_id;
st.read_data();
Defining Member Functions
(Inside the class definition)

• Member function is to replace the function


declaration by the actual function definition
inside the class definition.
• Syntax
ret_type fun_name(formal parameters)
{
function body
}
Defining Member Functions
(Outside the class definition)

• Using scope resolution operator ::


• :: tells the compiler that the function function-
name belongs to the class class-name.
• Syntax
ret_type class_name :: fun_name(formal parameters)
{
function body
}
#include <iostream>
using namespace std;

class Car {
public:
int speed(int maxSpeed);
};

int Car::speed(int maxSpeed) {


return maxSpeed;
}

int main() {
Car myObj;
cout << myObj.speed(200);
return 0; Output: 200
Arrays of Objects
• Several objects of the same class can be
declared as an array and used just like an array
of any other data type.

• The syntax for declaring and using an object


array is exactly the same as it is for any other
type of array.
• Syntax : class_nm obj_nm[number];
33, Joseph
Class Objects
St[0] S[0]
void read_data( )
S[1]
ex:
void print_data( )
S[2]
24, Sakshi
S[3]
S[4]
void read_data( )
S[5]
void print_data( )
S[6]
St[4] S[7]
Accessing Data Members
(outside the class)
• Syntax:(array of objects)

obj_name[i] . datamember;
ex: st[i].st_id;
Accessing Member Functions
• Syntax: (single object)

obj_name . Memberfunction(act_parameters);
ex: st.read( );

• Syntax:(array of objects)

obj_name[i] . Memberfunction(act_parameters);
ex: st[i].read( );
Inline Functions with Class
• Syntax: (Inside the class definition)
inline ret_type fun_name(formal parameters)
{
function body
}
Inline Functions with Class
• Syntax: (Outside the class definition)
inline ret_type class_name::fun_name (formal
parameters)
{
function body
}
Static Data Members
• Static data members of a class are also known
as "class variables“.

• Because their content does not depend on any


object.
• They have only one unique value for all the
objects of the same class.
• It is visible only within the class, but its lifetime
is the entire program.
Static Data Members
• Tells the compiler that only one copy of the variable
will exist and all objects of the class will share that
variable.

• Static variables are initialized to zero when the first


object is created. No other initialization is permitted

• Static variable have the same properties as global


variables but they enjoy class scope.
Declaration syntax: Class static_demo
Class class_name {
{ Static int x;
static type_var name_var; };
};
Definition syntax : to define outside the class
definition
<type_var> class_name :: <name_of static_var>;
Static Member Function
• Properties :
1) Static function can have access to only other
static members( functions or variables)
declared in the same class.
2) Static member function can be called using the
class name instead of its objects as follows :
class name :: function_name(parameter_list);
• Member functions that are declared with
static specifier.

Syntax:
class class_name
{
public:
static ret_dt fun_name(formal parameters);
};
int main()
{
#include < iostream>
test t1,t2;
Class test
t1.setcode();
{
t2.setcode();
Int code;
test::showcount();
Static int count;
test t3;
Public:
t3.setcode();
Void setcode(void)
test::showcount();
{ code=++count;}
t1.showcode();
Void showcode(void)
t2.showcode();
{ cout<<“object no.:”<<code;}
t3.showcode(); Output
Static void showcount(void)
Return 0; Count:2
{ cout<<“count:”<<count; }
} Count :3
};
Int test::count; Object number:1
Object number:2
Object number:3
Constructors
• A constructor is a ‘special’ member function
whose task is to initialize the objects of its
class.
• It is special because its name is the same as the
class name.
• Constructor is invoked whenever an object of
its associated class is created.
• It is called constructor because it constructs the
values of data members of the class.
Constructors
• A constructor function is a special member
function that is a member of a class and has
the same name as that class, used to create,
and initialize objects of the class.
• Constructor function do not have return type.
• Should be declared in public section.
• Invoked automatically when objects are
created
Constructors
Syntax: Example:
class class_name class student
{ { int st_id;
public: public:
class_name();
student()
};
{
st_id=0;
}
};
Constructors
• How to call this special function…?
class student
{
int main() int st_id;
{ public:
student st; student()
………… {
………… st_id=0;
}; }
};
Constructor can be defined inside the class declaration or
outside the class declaration

a. Syntax for defining the constructor within the class

<class-name>(list-of-parameters)
{
//constructor definition
}

b. Syntax for defining the constructor outside the class

<class-name>: :<class-name>(list-of-parameters)
{
//constructor definition
}
Characteristics of Constructors
• They should be declared in the public section.
• They are invoked automatically when the objects are
created.
• They do not have return types, not even void .
• They cannot be inherited, though a derived class can
call the base class constructor.
• Like c++ functions, they can have default arguments.
• Constructors cannot be virtual.
• We cannot refer to their addresses.
• They make implicit calls to the operators new and
delete when memory allocation is required.
// Example: defining the constructor within the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
};
int main()
{
student s; //constructor gets called automatically when we
//create the object of the class
s.display();
return 0;
}
// Example: defining the constructor outside the class
#include<iostream>
using namespace std;
class student
{
int rno;
char name[50];
double fee;
public:
student();
void display();
};
student::student()
{
cout<<"Enter the RollNo:";
cin>>rno;
cout<<"Enter the Name:";
cin>>name;
cout<<"Enter the Fee:";
cin>>fee;
}
void student::display()
{
cout<<endl<<rno<<"\t"<<name<<"\t"<<fee;
}
int main()
{
student s;
s.display();
return 0;
}
• Characteristics of the constructor:
• The name of the constructor is the same as its class name.
• Constructors are mostly declared in the public section of
the class though it can be declared in the private section of
the class.
• Constructors do not return values; hence they do not have
a return type.
• A constructor gets called automatically when we create the
object of the class.
• Constructors can be overloaded.
• Constructor can not be declared virtual.
• Constructor cannot be inherited.
• Addresses of Constructor cannot be referred.
• Constructor make implicit calls to new and delete operators
Types of Constructors
• Constructors with default argument : no
arguments
• Parameterized constructors : constructor that
can take arguments
• Copy constructors : accept a reference to its
own class as a parameter (object as a
argument)
• Dynamic Constructor : allocation of memory to
object at the time of their construction
Parameterized constructor
• Calling parameterized constructors :
1) By calling the constructor explicitly
e.g. demo d=demo(1,2);
2) By calling the constructor implicitly
e.g. demo d(1,2);
Parameterized Constructors
class Addition
{
meters
int num1; C o n st ru ctor wi t h
f
p
u
a
n
ra
ction!
o a
z it’s als
int num2; B’ Co

int res;
public:
Addition(int a, int b); // constructor
void add( );
void print(); Constructor that can take
}; arguments is called
parameterized constructor.
Overloaded Constructors
class Addition
{
int num1,num2,res;
n stru ctor with
float num3, num4, f_res; Overloaded CBo’Coz they are
ers
paramet ions!
public: also fun
ct

Addition(int a, int b); // int constructor


Addition(float m, float n); //float constructor
void add_int( );
void add_float();
void print();
};
Constructors with Default Argument
class Addition
{
int num1; Constru
ctor w i t h d efault

int num2; p arameter.

int res;
public:
Addition(); // constructor
void add( );
void print();
};
/ CPP program to illustrate the concept of Constructors
#include <iostream>
using namespace std;
class construct {
public:
int a, b;

// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
int main()
{
Construct c; // Default constructor called automatically when the object is created
cout << "a: " << c.a << endl << "b: " << c.b;
return 1;
}
Dynamic Constructors
Used to allocate memory at the time of object
creation

class Sum_Array
{
int *p;
public:
Sum_Array(int sz) // constructor
{
p=new int[sz];
}
};
Destructors
• A destructor function is a special function that
is a member of a class and has the same
name as that class used to destroy the objects
that have been created by a constructor.
• Must be declared in public section.
• Destructor do not have arguments & return
type.
NOTE:
A class can have ONLY ONE destructor
Destructors
Synatax: Example:
class class_name class student
{ {
public: public:
~student()
~class_name();
{
}; cout<<“Destructor”;
}
};
Local Classes
• A class defined within a function is called Local
Class.
void fun()
Syntax: {
void function() class myclass {
{ int i;
class class_name public:
{ void put_i(int n) { i=n; }
// class definition int get_i() { return i; }
} obj; } ob;
//function body ob.put_i(10);
} cout << ob.get_i();
}
Multiple Classes
Synatax: Example: Example:
class class_name1 class test class student
{ { int st_id;
{ public: test m;
//class definition int t[3]; public:
}; }; void init_test()
{
class class_name2
m.t[0]=25;
{ m.t[1]=22;
//class definition m.t[2]=24;
}; }
};
Nested Classes
Synatax: Example:
class student
class outer_class { int st_id;
{ public:
class dob
//class definition { public:
class inner_class int dd,mm,yy;
}dt;
{ void read()
//class definition {
dt.dd=25;
}; dt.mm=2;
dt.yy=1988;}
};
};
Friend Functions
• To make an outside function “friendly” to a
class, declare the function as a friend of the
class.
• Friend function is a non-member function which
can access the private members of a class

• To declare a friend function, its prototype


should be included within the class, preceding it
with the keyword friend.
Friend Functions
Example:
class myclass
{
Syntax: int a, b;
class class_name public:
{ friend int sum(myclass x);
//class definition void set_val(int i, int j);
public: };
friend rdt fun_name(formal parameters);
};
Friend Function
Characteristics:
• It is not in the scope of the class to which it
has been declared as friend.
• It can not be called using object of class
• Invoked like normal c++ function
• It can not access data members directly, has to
use object and dot operator (e.g. s.rno ).
• Can be declare in private or public section.
• Usually, It has the objects as arguments.
Void max (XYZ m,ABC
#include<iostream> n)
Class ABC; {
Class XYZ If(m.x>=n.a)
{ int x; Cout<<m.x;
Public: Else
Void setvalue(int i) {x=i;} Cout<<n.a;
Friend void max(XYZ,ABC); } Output
}; Int main() 20
Class ABC {
{ int a; ABC h;
Public: h.setvalue(10);
Void setvalue(int i) {a=i;} XYZ j;
Friend void max(XYZ,ABC); j.setvalue(20);
}; Max(h,j)
}
Pointers to Objects
student st; 51, Rajesh

student *ptr; void read_data( )

ptr = & st; void print_data( )

st
ptr 2FCD54
Pointers to Objects
• Pointers can be defined to hold the address of an
object, which is created statically or dynamically

Statically created object:


33, Joseph
student *stp;
stp = &st;
void read_data( )
Dynamically created object:
void print_data( )
student *stp;
stp = new student;
st
2FCDA4
Pointers to Objects
• Accessing Members of objects: using arrow pointer
operator ()
Syntax:
ptr_ob j  member_name;
ptr_obj  memberfunction_name( );

Example:
stp  st_name;
stp  read_data ( );
The this Pointer
• The this pointer points to the object that
invoked the function

• When a member function is called with an


object, it is automatically passed an implicit
argument that is a pointer to the invoking
object (that is, the object on which the
function is called).
The this Pointer
• Accessing Members of objects:
Syntax:
obj . memberfunction_name( );

this pointer points to st object


Example:
st . read_data ( );
Pointer to Class Member
• A special type of pointer that "points“
generically to a member of a class, not to a
specific instance of that member in an object

• Pointer to a class member is also called


pointer-to-member.
Pointer to Class Member
• It provides only an offset into an object of the
member's class at which that member can be
found.

• Member pointers are not true pointers, the .


and -> cannot be applied to them.

• A pointer to a member is not the same as a


normal C++ pointer.
Pointer to Class Member
• To access a member of a class:
Special pointer-to-member operators
1) .*
2) –>*
Pointer to Class Member
• Syntax to create pointer to data member
of a class:
Data_type class_name ::* data_member_ptr;
int student::*d_ptr;

• Syntax to create pointer to member function


of a class:
rtn_dt (class_name::* mem_func_ptr)(arguments);
int (student::*f_ptr)();

You might also like