0% found this document useful (0 votes)
13 views29 pages

CPP Unit 2

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)
13 views29 pages

CPP Unit 2

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/ 29

CM3104

UNIT 2 – BASICS OF OBJECT-ORIENTED PROGRAMMING

2.1 Tokens, Expressions and Control Structures Tokens, keywords, identifiers, constants and
symbolic constants, data types and its classifications, type casting,
2.2 Variables: introduction, declaration, dynamic initialization,reference.
2.3 Operators : introduction, scope resolution operator, type cast operator, memory
management operators, operator precedence
2.4 Expressions: introduction, types, special assignment Expressions
2.5 Access Specifiers: introduction, why there is need of access specifiers, types of access
specifiers.
2.6 Control structures : introduction, types of control structures like sequence structure,
selection structure, loop structure, example of all the types of structures like if-else, while,
do- while, for, switch with its syntax and usage.
2.7 Classes and Objects Classes: Introduction, use of classes in OOP, syntax to declare class,
local classes. Objects: introduction, memory allocation for objects, static data members,
array of objects, objects as function arguments, returning objects.
2.8 Constructors and Destructors Constructors : introduction, syntax, concept of memory
allocation using constructors, types of constructors, constructors with default arguments,
dynamic initialization of objects, dynamic constructors Destructors: introduction, syntax,
concept of memory deallocation using destructors, example.
***************************************************************************

Token
➢ The smallest individual units in a C++ program are known as tokens that is
meaningful to the compiler.
➢ C++ has the following tokens.
i. Keywords
ii. Identifiers
iii. Constants/Symbolic Constants
iv. Strings – Group of Characters
v. Operators

1|Page 186_SHRADDHA KESHAO BONDE


CM3104

Keywords
➢ It is reserved identifiers and cannot be used as names for the program
variables or other user defined program elements.

Identifiers
➢ A symbolic name is generally known as an identifier.
➢ Valid identifiers are a sequence of one or more letters, digits, or underscore
characters (_).
➢ Neither spaces nor punctuation marks or symbols can be part of an identifier.
➢ Only letters, digits and single underscore characters are valid.
➢ The rules for the formation of identifier - •An identifier may include of
alphabets, digits and/or underscores.
• It must not start with a digit and should not be a reserved word• C++
is case sensitive, i.e, upper case and lower-case letters are considered
totally different from each other.
• It may be noted that TOTAL and total are two different identifier
names.

Symbolic Constants
➢ Constants can be defined as the expression with fixed values.
➢ There are two ways of creating symbolic constants in c++.

2|Page 186_SHRADDHA KESHAO BONDE


CM3104

1. using the qualifier const. Ex- const int size = 10 ;


2. defining a set of integer constants using Enum keywords. Ex- enum
{x,y,z};
➢ In C++ if we want to make const value as global then declare as extern
storage class.Ex: external const total=100;

Data Types in C++


➢ Built-in Data Types

Built-in Data Types


➢ Built-in Data Types
1) int
2) float
3) double
4) char
5) void

Derived Data Types


➢ C++ also permits four types of derived data types.
➢ As the name suggests, derived data types are basically derived from the
built-in data types.

3|Page 186_SHRADDHA KESHAO BONDE


CM3104

➢ There are three derived data types. These are:


1) Array
2) Function
3) Pointer
4) Reference

User Defined Data Types


➢ C++ also permits four types of user defined data types.
➢ As the name suggests, user defined data types are defined by the
programmers during the coding of software development.
➢ There are four user defined data types. These are:
1) Structure
2) Union
3) Class
4) Enumerator
5) Typedef

Type Casting
➢ Type casting refers to the conversion of one data type to another in a
program.
➢ Typecasting can be done in two ways: automatically by the compiler and
manually by the programmer or user.
➢ Type Casting is also known as Type Conversion.
➢ There are Two types of type casting/Conversion
1. Implicit Type Casting or Implicit Type Conversion
2. Explicit Type Casting or Explicit Type Conversion

Implicit Type Casting or Conversion


➢ It is known as the automatic type casting.
➢ It automatically converted from one data type to another without any
external intervention such as programmer or user.

4|Page 186_SHRADDHA KESHAO BONDE


CM3104

➢ It means the compiler automatically converts one data type to another.


➢ All data type is automatically upgraded to the largest type without losing
any information.
➢ It can only apply in a program if both variables are compatible with each
other.
➢ char - sort int -> int -> unsigned int -> long int -> float -> double -> long
double, etc.
➢ Ex- int num = 20; char ch = 'a'; int res = 20 + 'a';

Explicit Type Casting or Conversion


➢ It is also known as the manual type casting in a program.
➢ It is manually cast by the programmer or user to change from one data
type to another type in a program. It means a user can easily cast one data
to another according to the requirement in a program.
➢ It does not require checking the compatibility of the variables.
➢ In this casting, we can upgrade or downgrade the data type of one
variable to another in a program.
➢ It uses the cast () operator to change the type of a variable.
➢ Syntax of the explicit type casting- (type) expression;
➢ Ex- int num;
num = (int) 4.534; // cast into int data type
cout << num;

Variables
➢ We might want to give a value a name so we can refer to it later. We do this
using variable. A variable is a named location in memory.
➢ For example, say we wanted to use the value 4 + 2 multiple times. We might
call it x and use it as follows:
# include < iostream >
using namespace std ;
int main () {
int x;
x = 4 + 2;
cout << x / 3 << ’ ’ << x * 2;

5|Page 186_SHRADDHA KESHAO BONDE


CM3104

return 0;}
➢ The name of a variable is an identifier token. Identifiers may contain
numbers, letters, and underscores (_), and may not start with a number.
➢ Line 4 is the declaration of the variable x. We must tell the compiler what
type x will be so that it knows how much memory to reserve for it and what
kinds of operations may be performed on it.
➢ Line 5 is the initialization of x, where we specify an initial value for it. This
introduces a new operator: =, the assignment operator. We can also change
the value of x later in the code using this operator.
➢ We could replace lines 4 and 5 with a single statement that does both
declaration and initialization: int x = 4 + 2;
➢ This form of declaration/initialization is cleaner, so it is to be preferred.

Declaration Of Variable
➢ In ANSIC C all the variable which is to be used in programs must be
declared at the beginning of the program. But in C++ we can declare the
variables any whose in the program where it requires.
➢ This makes the program much easier to write and reduces the errors that may
be caused by having to scan back & forth It also makes the program easier
to understand because the variables are declared in the context of their use.
➢ Example:
int main(){
float x, sum=0;
for(int i=1;i<5;i++){
cin>>x;
sum=sum+x
}
float average;
average=sum/x; cout<<average;
return 0;
}

Reference Variable
➢ C++ interfaces a new kind of variable known as the reference variable,
used for accessing & modifying value.
➢ A references variable provides an alias. (alternative name) for a previously
defined variable.
➢ For example, if we make the variable sum a reference to the variable total,
then sum and total can be used interchangeably to represent the variable.

6|Page 186_SHRADDHA KESHAO BONDE


CM3104

➢ A reference variable is created as follows:


➢ Syntax: Datatype & reference –name=variable name;
➢ Example: float total=1500; float &sum=total;
➢ Here sum is the alternative name for variables total, both the variables
refer to the same data object in the memory .
➢ Reference operator is ‘&’
➢ Reference Vs Pointer
➢ Reference Variable
➢ Example -
int x=5;
int &y=x;

Different types of Operators


(1)Arithmetic Operators
(2)Relational Operators
(3)Logical Operators
(4) Assignment Operators
(5)Increments and Decrement Operators
(6) Bitwise Operators
(7) Conditional Operator
Arithmetic Operators

Relational Operators

7|Page 186_SHRADDHA KESHAO BONDE


CM3104

Logical Operators
1. Logical AND (&&) :
Example:- a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole
expression is true only if both expressions are true i.e., if a is greater than b and
x is equal to 10.
2. Logical OR (||) :
Example : a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are
true. It evaluates to true if a is less than either m or n and when a is less than
both m and n.
3. Logical NOT (!) :
For example : ! (x >= y)
The NOT expression evaluates to true only if the
value of x is neither greater than or equal to y.
Truth Table:
Example : if(age > 55 && salary <
1000)
if(number < 0 || number > 100)

8|Page 186_SHRADDHA KESHAO BONDE


CM3104

Assignment Operators
Example : x + = 1 is same as x = x + 1 The commonly used shorthand
assignment operators are as follows:

Bitwise Operators
➢ ^ (XOR)
➢ | (OR)
➢ & (AND)
➢ ~ (complement)
➢ << (shift left, insertion to stream)
➢ >> (shift right, extraction from stream)

Conditional operator:
➢ This is the only ternary operator in C. The operator pair ?: is used to
construct conditional expression.
➢ Syntax: exp1 ? exp2 : exp3
Ex:
a = 10;
b = 15;
X = (a>b) ? a : b;
Here X will be assigned 15 i.e. the value of b.
Its same as
if (a > b)

9|Page 186_SHRADDHA KESHAO BONDE


CM3104

x = a;
else
x = b;

Increment and Decrement Operators


➢ C offers two unusual and unique operators ++ and - - called increment
and decrement operator respectively.
➢ The operators can be place either before or after the operand.
➢ If the operator is placed before the variable (++I or -–I) it is known as pre
incrementing or pre decrementing.
➢ If the operator is placed after post incrementing or post decrementing. the
variable (I++ or I–-) it is known as

Pre-Increment or Pre Decrement Operators


➢ In the pre increment or pre decrement first the value of operand is
incremented or decremented then it is assigned.
➢ Example:
x=100;
y=++x;
➢ After the execution the value of y will be 101 and the value of x will be 100.

New operators in C++

10 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

Memory management operators


➢ To avoid wastage of memory, you can dynamically allocate the memory
required during runtime using new and delete operator.
➢ new and delete operator perform the task of allocating and freeing the
memory in a better and easier way.
➢ New operator--The new operator in C++ is used for dynamic storage
allocation. This operator can be used to create object of any type.
Syntax: pointer- variable =new datatype;
Example: int *p=new int; float *q=new float;
➢ Delete operator--The delete operator in C++ is used for releasing memory
space when the object is no longer needed.
Syntax: delete pointer-variable;
Example: delete p; delete q;

Scope resolution operator in C


➢ In C++, scope resolution operator is :: It is used for below purposes
1) To define a function outside a class.
2) To access a class’s static variables.
3) In case of multiple Inheritance.
➢ Blocks and scopes can be used in constructing programs. We know same
variables can be declared in different blocks because the variables declared
in blocks are local to that function.

11 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

➢ It is used to uncover a hidden variable. Scope resolution operator allows


access to the global version of a variable.
➢ The scope resolution operator is used to refer variable of class anywhere in
program. :: Variable_name
OR
➢ Scope resolution operator is also used in classes to identify the class to
which a member function belongs. Scope resolution variable is used to
define function outside of class.
➢ Return_typeclass_name:: function_name( ) {…….. }

Operator Precedence

Header Files in C++


1)conio.h--if we use getch() and clrscr() in C++ program
2)iostream.h-- if you use cin and cout
Syntax–
#include<conio.h>
#include<iostream.h>

12 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

#include<math.h>

Expression with it’s type


➢ An expression is a combination of variables, constants, and operators written
according to the syntax of the language.
e.g. a+b, PI*r*r, (a+b) - c, (x/y) -z, 4a2 - 5b +c,
(a+b)*(x+y)
➢ Depending upon the type of operands involved in
an expression or the result obtained after
evaluating expression, there are different
categories of an expression.

Special Assignment Expressions


➢ In special assignment expressions, we have three types.
➢ Chained Assignment Expression - Chained Assignment expressions are
those expressions in which we assign the same value to more than one
variable in a single expression or statement.
• Ex- a = b = 80 and (x = y) = 44
➢ Embedded Assignment Expression – Embedded Assignment expressions are
those made up of assignment expressions enclosed by another assignment
expression.
• Ex- z = x + (y = 34); and z = (x = 44) + ( y = 4);
➢ Compound Assignment Expression- Compound Assignment Expressions are
those expressions that consist of assignment expressions and binary
expressions together. • Ex- z += x + (y = 34); and z += (x = 44) & ( y = 4);

Access specifiers
➢ In C++ Access specifies are also called as visibility mode. They are as
follows: Public, Private, and Protected .

13 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

➢ Public:- When access specifier is public i.e. base class is publicly inherited
by derived class all public member
of base class become public
members of derived class and all
protected members become
protected in derived class.
➢ Private: - All public and protected
members of base class become
private members of derived class.
➢ Protected: - In this all public and
protected members of base class
become protected of derived class
➢ If no access specifier is specified then it is treated by default as private
➢ The default access specifier of structure is public where as that of a class is
“private”

Need of Access specifiers


➢ Access modifiers are mainly used for encapsulation. It can help us to
control what part of a program can access the members of a class. So that
misuse of data can be prevented.
➢ It is used to set the accessibility of classes, constructors, methods, and
other members
➢ To ensure reusability
➢ The private members are most secure in inheritance.
➢ Private access specifier allows a class to hide its member variables and
member functions from other functions and objects.

Control Structures
➢ Control structures are portions of program code that contain statements
within them and, depending on the circumstances, execute these statements
in a certain way.
➢ There are typically two kinds: conditionals and loops.
1. Conditional Statement-
• If (Sequence statement)
• if-else (Sequence statement)
• else if (Sequence statement)
14 | P a g e 186_SHRADDHA KESHAO BONDE
CM3104

• Switch (Selection statement)


2. Loop Statement- Conditionals execute certain statements if certain conditions
are met; loops execute certain statements while certain conditions are met. C++
has three kinds of loops:
• While
• Do while
• For

If conditional statement
➢ The if conditional has the form:
if(condition)
{
statement1 statement2 …
}
➢ The condition is some expression whose value is being tested. If the
condition resolves to a value of true, then the statements are executed before
the program continues on. Otherwise, the statements are
ignored. If there is only one statement, the curly braces may be omitted,
giving the form:
if(condition)
Statement;

if-else conditional statement


➢ The if-else form is used to decide between two sequences of statements
referred to as blocks:
if(condition){statementA1
statementA2
…}
else {statementB1
statementB2 …
}
➢ If the condition is met, the block corresponding to the if is executed.
Otherwise, the block corresponding to the else is executed. Because the
condition is either satisfied or not, one of the blocks in an if-else must
execute. If there is only one statement for any of the blocks, the curly braces
for that block may be omitted:
15 | P a g e 186_SHRADDHA KESHAO BONDE
CM3104

if(condition) statementA1
else
statementB1

else if conditional statement


➢ The else if is used to decide between two or more blocks based on multiple
conditions:
if(condition1){
statementA1; statementA2; …
}else if(condition2){
statementB1; statementB2;
……. }
➢ If condition1 is met, the block corresponding to the if is executed. If not,
then only if condition2 is met is the block corresponding to the else if
executed. There may be more than one else if, each with its own condition.
Once a block whose condition was met is executed, any else ifs after it are
ignored. Therefore, in an if-else-if structure, either one or no block is
executed.
➢ An else may be added to the end of an if-else-if. If none of the previous
conditions are met, the else block is executed. In this structure, one of the
blocks must execute, as in a normal if- else.

Switch-case conditional / Selection statement


➢ The switch-case is another conditional structure that may or may not
execute certain statements. However, the switch-case has peculiar syntax
and behavior
switch(expression){
case constant1: statementA1
statementA2
... break;
case constant2: statementB1
statementB2
... break; ... default: statementZ1
statementZ2
... }
➢ The switch evaluates expression and, if expression is equal to constant1,
then the statements beneath case constant 1: are executed until a break is
encountered.

16 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

➢ If expression is not equal to constant1, then it is compared to constant2.


➢ If these are equal, then the statements beneath case constant 2: are executed
until a break is encountered. If not, then the same process repeats for each
of the constants, in turn.
➢ If none of the constants match, then the statements beneath default: are
executed.
➢ Due to the peculiar behavior of switch-cases, curly braces are not necessary
for cases where there is more than one statement (but they are necessary to
enclose the entire switch-case).
➢ switch-cases generally have if-else equivalents but can often be a cleaner
way of expressing the same behavior.

while statement
➢ The while loop has a form similar to the if conditional:
while(condition){
statement1
statement2
….……. }
➢ As long as condition holds, the block of statements will be repeatedly
executed. If there is only one statement, the curly braces may be omitted.
Here is an example:
#include <iostream>
using namespace std;
int main() {
int x = 0; 6
while(x < 10)
x = x + 1;
cout << "x is " << x << " \n ";
return 0; }
➢ This program will print x is 10.

Do while statement
➢ The do-while loop is a variation that guarantees the block of statements will
be executed at least once:
do
{
statement1 statement2 …
17 | P a g e 186_SHRADDHA KESHAO BONDE
CM3104

}
while(condition);
➢ The block of statements is executed and then, if the condition holds, the
program returns to the top of the block.
➢ Curly braces are always required. Also note the semicolon after the while
condition

For statement
➢ The for loop works like the while loop but with some change in
syntax: for(initialization; condition; increment){
statement1
statement2 …
}
➢ The for loop is designed to allow a counter variable that is initialized at the
beginning of the loop and incremented (or decremented) on each iteration of
the loop. Curly braces may be omitted if there is only one statement. Here is
an example:
#include <iostream>
using namespace std;
int main() {
for(int x = 0; x < 10; x++)
cout << x << " \n " ;
return 0; }
➢ This program will print out the values 0 through 9, each on its own line

Nested Control statement – if else nesting


➢ It is possible to place ifs inside of ifs and loops inside of loops by simply
placing these structures inside the statement blocks. This allows for more
complicated program behavior.
➢ Here is an example using nesting if conditionals:
#include <iostream>
using namespace std;
int main() {
int x = 6;
int y = 0;
if(x > y) {
cout << “x is greater than y\n”;
18 | P a g e 186_SHRADDHA KESHAO BONDE
CM3104

if(x == 6) cout << “x is equal to 6\n”;


else cout << “x is not equalt to 6\n”;
} else
cout << “x is not greater than y\n”;
return 0;
}

Nested Control statement – loop nesting


➢ Here is an example using nested loops:
#include <iostream>
using namespace std;
int main() {
for(int x = 0; x < 4; x = x + 1) {
for(int y = 0; y < 4; y = y + 1)
cout << y;
cout << “\n”; 9
}
return 0;
}
➢ Output- This program will print four lines of 0123.

Class
➢ Class is a group of objects that share common properties &relationships
➢ Class is a collection of objects.
Or
A class is a blueprint of the object.
➢ Generally a class specification has two parts:-
Class declaration
Class function definition
➢ Syntax:-
class class-name{
private:
variable declarations;
function declaration ;
public:
variable declarations;
function declaration;
};

19 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

➢ Example
class item {
private:
char name [30];
float cost;
public:
void getldata (char a[] ,float b);
void putdata (void);
};

Objects
➢ Definition : Objects are basic run time entities in an object oriented system.
➢ They may represent a person, a place, a bank account, a table of data or any
item that the program has to handle.
➢ An object is the instance of the class.
➢ Object can be declared same as the variable declaration.

Declaring objects
➢ The declaration of object is same as declaration of variables of basic data
types.
➢ Defining objects of class data type is known as class instantiation.
➢ Memory is allocated only when objects are created.
➢ Syntax: class_name variable_name;
➢ Ex: student s;
student s1,s2, *s3; // declaration of object or class type variablesWhere
s1, s2, s3 are three objects of class student .
*s3 is a pointer to class student.

Defining member function


➢ Member function can be defined in two places”
1. Outside the class definition
2. Inside the class definition
➢ The function should perform the same task irrespective of the place of
definition.

20 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

Memory allocation for object


➢ The memory space for object is allocated when they are declared and not
when the class is specified.
➢ Member function are created and placed in the memory space only once
when they are defined as a part of a class definition.
➢ Since all the objects belonging to that class use the same member
function, no separate space is allocated for member functions.
➢ When the objects are created only space for member variable is allocated
separately for each object.
➢ Separate memory locations for the objects are essential because the
member variables will hold different data values for different objects this
is shown in fig:

Static Data Member


➢ Following are the characteristics of static member
• It is initialized to zero when the first object of its class is created. No
other initialization is permitted
• Only one copy of that member is created for the entire class so known as
class variable and is shared by all the object of that class, no matter how
many objects are created.
• It is visible only within class, but its lifetime is the entire program.
Static variables are used to maintain values common to the entire class.
• Each static variable must be defined outside the class definition. Static
data members are stored separately rather than as a part of an object.

21 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

• A static member function can have access to only other static members
declared in the same class.
• A static member function can be called using the class name:
Class_name::function_name;
• Syntax:
1)Inside the class:
static datatype variblename;
Eg:static int a;
2)outside the class:
return_type classname::variablename;
eg-int student::a;
int student::a=5;
➢ Use of static data member:
• Static data member (variable) is used to maintain values common to the
entire class.
• Only one copy of static member is created for the entire class and is
shared by all the objects of that class.
• Its lifetime is the entire program.

Array of Object
➢ Array of a Variables that are of type class are called array of object.
➢ The arrays can be used as member variables in a class.
➢ An array is a collection of same data type or group of data item that stored in
a common name.
➢ Syntax: classname objectname[size];
➢ Example: 1.student s[10];
employee E[3];
(three objects E[0], E[1], E[2] are created)

22 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

Objects as function arguments


➢ Object can be used as function argument to share the data and functions
associated with that object & this is done by two ways.
1. A copy of the entire object is passed to the function
• The first method is called pass-by-value
• A copy of a object is passed to the function any changes made to the
object inside the function do not affect the object used to call the
function
2. Only the address of the object is transferred to the function
• The second method is called pass-by- reference.
• When an address of the object is passed, the called function directly
work on actual object used in the call.
• Any changes made to the object inside the function will reflect in the
actual object.

Returning an Object
➢ An object is an instance of a class. Memory is only allocated when an object
is created and not when a class is defined.
➢ An object can be returned by a function using the return keyword.
➢ A function can also return objects either by value or by reference.
➢ When an object is returned by value from a function, a temporary object is
created within the function, which holds the return value.
➢ This value is further assigned to another object in the calling function.

Constructor in C++
➢ Constructor is a member function of the class.
➢ It is called special member function because the name of the constructor
is same as name of the class.
➢ Constructor is used to construct the values for the data member of the
class automatically when the object of class is created.
➢ Like other member function there is no need to call constructor explicitly.
It is invoked automatically each time the object of its class is created.
➢ Every class having at least one constructor defined in it. If you do not
define any constructor in the class then compiler will automatically create
a constructor inside the class and assigns default value (0) to the data
member of the class.

23 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

Characteristics of constructor
➢ It is called automatically when object of its class is created.
➢ It does not return any value.
➢ It must be declared inside public section of the class.
➢ It can have default arguments.
➢ Inheritance of constructor is not possible.
➢ It can not virtual.
➢ Constructor is invoked whenever an object of its associated class is
created.
➢ Disadvantage of default constructor –
➢ Each time an object is created it will assign same default values to the
data members of the class.
➢ It is not possible to assign different values to the data members for the
different object of the class using default constructor.

Concept Of Memory Allocation Using Constructor


➢ C++ supports these functions and also has two operators new and delete,
that perform the task of allocating and freeing the memory in a better and
easier way.
➢ Ex- int *p = new int[10]

➢ It allocates enough memory to hold an object of the type requested and It


calls a constructor to initialize an object in the memory that was
allocated.
➢ The memory of the required size is allocated in the heap segment of the
memory using the new operator.
➢ The class constructor is invoked to initialize the allocated memory
segment properly, and the allocated memory can be stored in a pointer.
➢ A constructor does not allocate memory for the class object its this
pointer refers to, but may allocate storage for more objects than its class
object refers to.
➢ If memory allocation is required for objects, constructors can explicitly
call the new operator.

24 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

➢ A constructor is a method. As such, it takes a static amount of memory


when compiled and eventually gets called with different instances of your
class.
➢ When you call a constructor function, your runtime allocates memory for
an instance of your class and passes that instance to the constructor
method, which initializes the object according to its parameters.
➢ In C++, memory is divided into two parts -
➢ Stack - All the variables that are declared inside any function take
memory from the stack.
➢ Heap - It is unused memory in the program that is generally used for
dynamic memory allocation.

Types of constructor
➢ Default constructor
➢ Parameterised constructor
➢ Copy constructor
➢ Dynamic constructor

Default constructor
➢ A constructor that accepts no parameters is called the default constructor.
➢ If default constructor is not defined in program then the compiler supplies
a default constructor
➢ Constructor declaration wit Exclass student {
int rollno;
char name[20];
public: student();
};
➢ Constructor definition--
student::student(){ rollno=0; name=”Priya”; }
➢ Constructor calling–
void main(){ student s; .... }
➢ Constructor can be defined inside class as shown below:class Rectangle {
int Height, Width;
public: Rectangle(){
Height = Width = 1;
}
};
25 | P a g e 186_SHRADDHA KESHAO BONDE
CM3104

➢ Constructor can be defined outside class as shown below:class


Rectangle{
int Height, Width;
public:
Rectangle();
};
Rectangle :: Rectangle(){ Height = Width = 1; }

Parameterized Constructor
➢ It is possible to pass arguments to constructor functions. These arguments
help to initialize an object when it is created.
➢ To create parameterized constructor, simply add parameters to the
constructor function and when you define the constructors body use
parameters to initialize objects.
➢ The constructor that can take arguments are called parameterized
constructor.
➢ Parameterized Constructor Declaration With Exclass student{
int rollno;
char name[20];
public:
student(int rn, char nm[20]);
};
➢ Parameterized Constructor definition--
student::student(int rn, char nm[20]){
rollno=rn; strcpy(name,nm); }
➢ Constructor calling–
void main(){
student s(1,”abc”), s2(2,”aa”);
........ }

Copy constructor
➢ The process of copying one object data in to another object is called as
Copy Constructor.
➢ A copy constructor is a constructor which is used to initialize the current
values with another object value.
➢ Copy constructor is used to create another Copy or Xerox of one object.
➢ A copy constructor takes a reference to an object of the same class as
itself as an argument.

26 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

➢ Copy constructors are having class type parameters means object.


➢ Copy constructors receives another object to initialize current object

Overloaded/Multiple Constructor
➢ Multiple constructors is a category of constructor in which a class can
have more than one constructor. This is also known as constructor
overloading.
➢ All constructors are defined with the same name as the class name they
belong to.
➢ Each of the constructors contains different number of arguments or
different data type of arguments.
➢ Depending upon the number of arguments and their data type, the
compiler executes appropriate constructor.

Constructor with default argument


➢ It is possible to define constructor with default argument.
➢ For eg- student(int rn, float per=80);
➢ The default value of argument per is 80. then the
statement - student s(2);
➢ Which assigns the value 2 to rn and 80 to per(by default).
➢ Initialization of default value to variable is done only in function
declaration or function definition not in both.
➢ Default argument is written after normal argument
➢ For eg--
student(int rn, float per=80); //correct
student( float per=80,int rn); //wrong

Dynamic Object
➢ An object that is created at run time is called as a dynamic object.
➢ The construction & destruction of dynamic object is explicitly done by
the programmer using new and delete operators.
➢ A dynamic object can be created using new operator.
ptr = new class_name;
➢ Where the variable ptr is a pointer object of the same class the new
operator returns the object created and it is stored in the pointer ptr.
delete object syntax is : delete ptr;

27 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

Dynamic Constructor
➢ When allocation of memory is done dynamically using dynamic memory
allocator new in a constructor, it is known as dynamic constructor.
➢ This allows us to initialize objects dynamically.
➢ The term dynamic constructor is used when memory allocation is done
dynamically inside a constructor using the keyword new.
➢ The dynamic constructor will not create any memory for the object.
However, it creates a memory block that the objects could access.

Destructors in C++
➢ When ever constructor is executed object is defined and memory is
allocated.
➢ Now to release (or) delete this memory we use destructor.
➢ Destructor is also one special member function, which is used to delete
the memory created by the constructor.
➢ Constuctor constructs the memory (or) Constructor constructs the object
data.
➢ Destructor is used to delete this memory created by constructor.
➢ Using destructors is a good practice because it automatically release the
memory occupied by the constructor.

Characteristics of Destructors
➢ Destructor name should be similar to class name and preceded by 'tilde'
operator(~).
➢ Ex: class sample {
sample() { ----------- } //constructor
~sample() { ---------- } //Destructor };
➢ Destructor should be declared in public section.
➢ They are invoked automatically when object goes out of scope.
➢ Destructor doesn't have any arguments/default arguments, so overloading
is not possible.
➢ Destructor never returns a value, it makes a implicit call new and delete
operator.
➢ Destructor never called with object followed by dot(.) operator.
➢ Destructor never participate in inheritance.

28 | P a g e 186_SHRADDHA KESHAO BONDE


CM3104

Differentiate between contractor and destructor.

Difference between structure and class

********************************************************

29 | P a g e 186_SHRADDHA KESHAO BONDE

You might also like