Top Banner
UNIT-V UNIT-V 1. introduction to c++ programming – 1. introduction to c++ programming – 2. object oriented programming concepts, 2. object oriented programming concepts, 3.Structured Vs OOP. 3.Structured Vs OOP. 4.Classes and objects-class definition 4.Classes and objects-class definition 5. Objects 5. Objects 6. class scope and accessing members 6. class scope and accessing members 7. Constructors-default constructor 7. Constructors-default constructor 8. parameterized constructor 8. parameterized constructor 9. constructor initialization list 9. constructor initialization list 10.copy constructor 10.copy constructor 11. Destructors 11. Destructors . . Sathi Durga Devi, Department of IT,SNIST
59

Unit v(dsc++)

Apr 13, 2017

Download

Engineering

Durga Devi
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Unit v(dsc++)

UNIT-VUNIT-V

1. introduction to c++ programming – 1. introduction to c++ programming – 2. object oriented programming concepts,2. object oriented programming concepts,3.Structured Vs OOP.3.Structured Vs OOP.4.Classes and objects-class definition4.Classes and objects-class definition5. Objects5. Objects6. class scope and accessing members6. class scope and accessing members7. Constructors-default constructor7. Constructors-default constructor8. parameterized constructor8. parameterized constructor9. constructor initialization list 9. constructor initialization list 10.copy constructor 10.copy constructor

11. Destructors11. Destructors..

Sathi Durga Devi, Department of IT,SNIST

Page 2: Unit v(dsc++)

History of C++ Extension of C Early 1980s: Bjarne Stroustrup (Bell Laboratories) Originally named “C with Classes”. Provides capabilities for object-oriented programming.

• Objects: Reusable Software Components– Model items in real world

• Object-Oriented Programs– Easy to understand, correct and modify

Hybrid language• C-like style• Object-oriented style• Both

Sathi Durga Devi, Department of IT,SNIST

Page 3: Unit v(dsc++)

Procedure-Oriented programming/ structured oriented programming

• To do a particular task the list of instructions are given to the computer to follow, and organizing these instructions into groups known as functions. Such languages are called procedure- oriented programming.

• COBOL, FORTRAN, C is commonly known as procedure- oriented programming (POP).

Sathi Durga Devi, Department of IT,SNIST

Page 4: Unit v(dsc++)

Procedure-oriented programming

Sathi Durga Devi, Department of IT,SNIST

Main program

Function-5

Function-2 Function-3

Function-4

Function-1

Function-6 Function-7 Function-8

Page 5: Unit v(dsc++)

Relationship of data and functions in procedural programming

Sathi Durga Devi, Department of IT,SNIST

Global data Global data

Function-1

Local data

Function-2

Local data

Function-3

Local data

Page 6: Unit v(dsc++)

/* Write a c program to implement the selection sort*/#include<stdio.h>void select_sort(int x[], int size);int find_min(int x[],int k,int size);int n,size,a[10],i,j,x,k,pass,temp,min,loc; -> global datavoid main() {

printf("\nEnter the size of array: ");scanf("%d",&n);printf("\nEnter the array elements: ");for(i=0;i<n;i++)

scanf("%d",&a[i]);printf("\nElements in array before swapping: ");for(i=0;i<n;i++)

printf("\t%d",a[i]);printf("\n");select_sort(a,n);printf("\n\n\tElements after swapping: ");for(i=0;i<n;i++)

printf("\t%d",a[i]);getch();

}

Sathi Durga Devi, Department of IT,SNIST

Page 7: Unit v(dsc++)

void select_sort(int x[],int size){

for(k=0;k<n;k++){loc = find_min(x,k,size);

temp=x[k];x[k]=x[loc];x[loc]=temp;

}}

int find_min(int x[],int k,int size){

min=x[k];loc=k;for(j=k+1;j<=size-1;j++){

if(min>x[j]){

min=x[j];loc=j;

}}return loc;

}

X, k, size are local data to function selection sort

Sathi Durga Devi, Department of IT,SNIST

Page 8: Unit v(dsc++)

Characteristics of procedure-oriented programming Emphases on algorithms Large programs are divided into smaller programs

known as functions/procedures. Procedures\ functions are independent of each other. Most of the functions share global data Functions transform data from one form to another Employs top-down approach in program design- instead

of writing one long list of instructions and execute from start to end, we can separate out the instructions into the functions it is called top- down approach.

Sathi Durga Devi, Department of IT,SNIST

Page 9: Unit v(dsc++)

Advantages of Procedural Programming:• Its relative simplicity, and ease of implementation of

compilers and interpreters.• The ability to re-use the same code at different places in

the program without copying it. • An easier way to keep track of program flow. • The ability to be strongly modular or structured. • Needs only less memory. Disadvantages of Procedural Programming:• Works well for the smaller projects.• Difficult to maintain when code gets larger.• Data is exposed to whole program, so no security for data.• Difficult to relate with real world objects.• More difficult to debug large programs.• Importance is given to the operation on data rather than

the data.

Sathi Durga Devi, Department of IT,SNIST

Page 10: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

A way of viewing the world • In order to clearly understand the object orientation, let’s

take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals send through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it.

Page 11: Unit v(dsc++)

Object-oriented programming Oops decompose the problem into number of entities called

objects and it contains the data and functions

Sathi Durga Devi, Department of IT,SNIST

Object A Object B

Data

Functions

Data

Functions

Data

Functions

Object C

communication

Page 12: Unit v(dsc++)

Characteristics of object-oriented programming• Emphasis on data rather than procedure• Programs are divided into objects• Functions that operate on the data of an object

are tied together in the data structure• Data is hidden and cannot be accessed by

external functions• Objects may communicate with each other

through functions• New data and functions can be easily added

whenever necessary.• Example are java,c++, smalltalk etc.

Sathi Durga Devi, Department of IT,SNIST

Page 13: Unit v(dsc++)

Advantages of oops• simplicity: software objects model real world objects, so the

complexity is reduced and the program structure is very clear;

• modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program.

• extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones;

• OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones.

• maintainability: objects can be maintained separately, making locating and fixing problems easier;

• re-usability: objects can be reused in different programs. • Software complexity is managed easily.• Builds secured programs due to data hiding.Sathi Durga Devi, Department of

IT,SNIST

Page 14: Unit v(dsc++)

Pops vs oops

Sathi Durga Devi, Department of IT,SNIST

Procedure Oriented Programming Object Oriented Programming1. Emphases on algorithm 1. Emphases on data2. Gobal data accessible to all the functions . Hence , it reduces the security

2. Data is hided and localizes the data and restrict other objects

3. Modules 3. Objects4. Variables Attributes5. Calling 5. Messaging6. Top- down approach 6. Bottom- up approach

Page 15: Unit v(dsc++)

object oriented programming conceptsobject oriented programming concepts1.Objects1.Objects2. Classes2. Classes3.Data abstraction and Encapsulation3.Data abstraction and Encapsulation4. Inheritance4. Inheritance5. Polymorphism5. Polymorphism6. Dynamic Binding6. Dynamic Binding7. Message passing7. Message passing

Sathi Durga Devi, Department of IT,SNIST

Page 16: Unit v(dsc++)

1. Objects

Object is instance of a class. Objects are basic run-time entities in an object-

oriented system and it contains the data and functions. In this an object is considered to be a partitioned area

of computer memory that stores data and set of operations that can access that data. Since the memory partitions are independent, the objects can be used in variety of programs without modification and provides more security.

Objects interacts with each other by sending messages.

Sathi Durga Devi, Department of IT,SNIST

Page 17: Unit v(dsc++)

State and behavior of an object• Every object has a state. That is, at any point in time it can

be described about what data it has. ex- class person to store the following data about the person:

name, address, color, height, weight, when a person object is created it stores the data about him. These are call state of an object.

• An object can perform a set of related activities. The set of activities that the object performs defines the object's behavior.

• Every object has behavior. That is, an object has a certain set of actions that it can perform

ex- for average marks of a student, call the method average();

Sathi Durga Devi, Department of IT,SNIST

Page 18: Unit v(dsc++)

2. class• A class is collection of objects are of similar type,

where the variables and methods are defined.• Ex: fruit mango;

• Example- Apple, orange,banana are of type class fruit.

• Each object is associated with the data of type class. • Classes are user-defined data types and behave like

the built-in types of programming language• Objects which follows the definition of the class is

called instances of the class.

Sathi Durga Devi, Department of IT,SNIST

class object

Page 19: Unit v(dsc++)

3.Data Encapsulation The wrapping up of data and functions into a

single unit is known as encapsulation The class is used to achieve the encapsulation. The data is not accessible to the outside world,

and only those functions which are wrapped in the class can access it

So it achieves data hiding or information hiding.

Sathi Durga Devi, Department of IT,SNIST

Page 20: Unit v(dsc++)

Data abstraction- it refers to provide only essential features to the outside world and hiding their background details

Abstraction shows only what it does rather than how it does or works.

Sathi Durga Devi, Department of IT,SNIST

4. InheritanceInheritance is the process by which objects of one class acquire the properties of another class.Inheritance is a mechanism of reusing and extending existing classes without modifying them. usesIt support the concept of hierarchical classificationSupports the reuse the software components ( reusability).Increases reliability and decreases the maintenance cost.

3. Data Abstraction

Page 21: Unit v(dsc++)

5. polymorphism• A Greek term, means that ability to take more than one form.• Polymorphism relates to object methods.• A method may exhibit different behaviors in different instances.• Behaviour depends on the types of data used in the operations.• All the objects share the same function name but their implementation is

differ.• Polymorphism used to implement the inheritance.

Sathi Durga Devi, Department of IT,SNIST

ShapeDraw()

Circle objectDraw()

Box objectDraw()

TriangleDraw()

Page 22: Unit v(dsc++)

Why this oops are better to model the real world objects?Example- Ram- raju r u hungry?Raju- yes, I am .Here Raju and Ram are two objects they send messages like raju

r u hungry and yes I am If you ask same question to the robot as different object it gives

different answer.- Objects are created based on how to respond to the messages.- Different objects might respond to same message in different

ways.- This can be achieved by the polymorphism

Sathi Durga Devi, Department of IT,SNIST

Page 23: Unit v(dsc++)

7. Message passing• Set of objects that communicate with each other. 1. create the classes that define data and functions. 2. creating the objects for that class 3. establish communication among objects. exampleaccount. Balance_enquiry(accountno);

Object message information

Sathi Durga Devi, Department of IT,SNIST

6. Dynamic binding

Linking of procedure call to the code to be executed in response to the call. In which the code associated with the given procedure call is not known until time of run- time of a program is called dynamic binding.

Page 24: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Benefits of OOPThrough inheritance, we can eliminate redundant code and extend the use of existing classes.

The principle of data hiding helps the programmer to build secure programs that cannot be invaded by code in the parts of the program.

It is easy to partition the work in a project based on objects.

Object oriented system easily upgraded from small to large systems.

Software complexity can be easily managed.Applications of OOPReal-time systems.Object-Oriented Databases.Neural Networks and Parallel Programming.Decision Support and Office Automation Systems.

Page 25: Unit v(dsc++)

I/O in C++

Since C++ is a superset of C, all of the C I/O functions such as printf and scanf which are found in the stdio.h header file, are still valid in C++.

C++ provides an alternative with the new stream input/output features by including “iostream.h”.

Several new I/O objects available when you include the iostream header file. Two important ones are:

cin // Used for keyboard input cout // Used for screen output

Both cin and cout can be combined with other member functions for a wide variety of special I/O capabilities in program applications.

Sathi Durga Devi, Department of IT,SNIST

Page 26: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Since cin and cout are C++ objects, they are somewhat "intelligent": They do not require the usual format strings and conversion specifications. They do automatically know what data types are involved. They do not need the address operator, &. They do require the use of the stream extraction (>>) and insertion (<<)

operators. Example with cin and cout:

// program to find average of two numbers#include<iostream.h>void main(){

float n1,n2,avg;cout<<”Enter two values\n”;cin>>n1>>n2;avg = (n1+n2)/2;cout<<”\nAverage is “<<avg;

}

Page 27: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

• A sample C++ program

-cout is a predefined object that represents the standard output stream in C++. Here the standard output stream represents the screen.

-The operator << is called the insertion or put to operator. It inserts the content on its right to the object on its left.

-we have used #include<iostream.h>. It contains the declarations for the cout and the operator <<.

-The header file iostream should be included at the beginning of all programs that use input/output statements.

#include<iostream.h>void main(){ cout<<” Hello World”;}

Page 28: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

• A sample C++ program// program to find average of two numbers#include<iostream.h>void main(){ float n1,n2,avg; cout<<”Enter two values\n”; cin>>n1>>n2; avg=(n1+n2)/2; cout<<”\nAverage is “<<avg;}

• cin is a predefined object that represents the standard input stream in C++. Here the standard input stream represents the keyboard.

• The operator >> is known as extraction or get from operator. It extracts the values from the keyboard and assigns it to the variables on its right.

• At a time, more than one variable can be read using cin. • The multiple use of << (along with cout) or >> (along with cin) in one

statement is called cascading

Page 29: Unit v(dsc++)

Implementing classes and objects• Class:- the class is basis for the oops. Class is a expanded concept of data structure, where it

holds both data and functions. The class is used to define the nature of an object, and also it is basic unit for the encapsulation.

-> the class combines the data and its associated functions together. It allows the data to be hidden.

-> the keyword class is used to create a class. The class declaration defines the new data type used to create the objects of that type.

Class has two parts:1. Data members declaration 2. Prototype of member function declarations

Note: Data members can’t be initialized with in the class. They can be initialized using member functions.

Sathi Durga Devi, Department of IT,SNIST

Page 30: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Syntax of declaring a class:class class-name {

access-specifier:data and functions;

access-specifier:data and functions;

// ...access-specifier:

data and functions;}object-list;

-When defining a class, we are creating a new abstract data type that can be treated like any other built-in data type.

Class should enclose both data declaration and function declaration part between curly parenthesis and class definition should be ended with semicolon.

Members (data members and member functions) are grouped under access specifiers, namely private, public and protected, which define the visibility of members.

Data which is declared in a class is by default treated as private which can be accessed only to the functions which are declared inside of the same class.

The object-list is optional. If present, it declares objects of the class

Page 31: Unit v(dsc++)

class: item

Data

number

cost

Functions

getdata()

putdata()(a)

getdata()

putdata()

item

(b)

number

cost

Representation of class

Data members are number and cost member functions are getdata(), putdata() data members + member functions- members of the class.

Sathi Durga Devi, Department of IT,SNIST

Page 32: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Creating objects The process of creating objects of a class is called class instantiation. Object is instance of the class. Once the class is created we can create any number of objects.

class class-name{

------;------;

}object-list;

class student{

------;------;

}s1,s2,s3;

class_name object-name1,object-name2,object-name3;

student s1, s2, s3;

Syntax1: Example1:

Syntax2:

Example2:

Page 33: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Accessing class members:

Once an object of a class has been created, then we can access the members of the class. This is achieved by using the member access operator, dot(.).

Syntax:Object-Name.DataMember;Object-Name.Memberfunction(arguments);

Example:x.getdata(10,20);x.number;

Here x.number accessing is illegal, if number is private data member of the class. Private data members are accessed only through the member functions not directly by objects.

Page 34: Unit v(dsc++)

Structure of C++ program:

Sathi Durga Devi, Department of IT,SNIST

Include files

Class declaration

Member functions definitions

Main function program

Page 35: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Access control specifiersThe following are the access control specifiers. 1. Private 2. public 3. protected.1. Private members: Private members of a class have strict access control. Only the member functions of the same class can access these members. They prevents the accidental modifications from the outside world. Example: class person { private:

int age;int getage();

};

Access- control specifiers- determines the accessibility of the members of the class.

person p1; int a=p1.age; //error p1.getage(); // error p1.age=5; // error

A private member functions is only called by the member function of the same class . Even an object cannot invoke a private function using the dot operator.Note- by default are members in a class are private – using keyword private is optional.

Page 36: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

2. Public members

All members declared with public can have access to outside of the class without any restrictions

Ex- class person { public:

int age;int getage();

}; person p1; a=p1.age;//correct p1.getage();// correct

Page 37: Unit v(dsc++)

3. Protected: Similar to the private members and used in inheritance. The members which are under protected, can have access to the members

of its derived class.Example: class A

{private:

//members of Aprotected:

//members of Apublic:

//members of A};class B: public A //Here class B can have access on { protected data of its parent class as

//members of B well as public data.};

Sathi Durga Devi, Department of IT,SNIST

Page 38: Unit v(dsc++)

Visibility of the class members

Sathi Durga Devi, Department of IT,SNIST

Access specifiers own class members objects of class

Private yes No

Public yes yes

Protected yes No

Page 39: Unit v(dsc++)

#include <iostream.h> #include <string.h>class student{ public: string name; int rollno; }; int main() { student a, b; a.name = "Calvin"; b.name = "Hobbes"; a.rollno = 4 01; b.rollno= 402; cout << a.name << ": " << a.rollno << endl; cout << b.name << ": " << b.rollno << endl; return 0; }

Sathi Durga Devi, Department of IT,SNIST

endl in c++ is similar to the \n in c language.

Page 40: Unit v(dsc++)

Defining the member functionsFunctions are defined in two ways 1. outside the class definition 2. inside the class definition 1. outside the class definition if a member function is declared within the class, it may also defined out side

of the class. General form is

Sathi Durga Devi, Department of IT,SNIST

Return_type classname:: functionname(argmlist){ --------}

:: - scope resolution operator tells to the compiler that which function belongs to which class in the program.

It uses the scope resolution operator :: to define a function out side of the class.

2. inside the class definition- functions are directly defined inside of the class definition.

Page 41: Unit v(dsc++)

#include<iostream.h>#include<string.h> class student { private:

int rollno;char name[30];

public:void setdata(int rn, char *n)void putdata()

};

void student :: setdata(int rn, char *n){

rollno=rn;strcpy(name, n);

}void student :: putdata(){

cout<<“roll o=“<<rollno<<“\n”;

cout<<“name=“<<name<<“\n”;}

Example on functions defined outside the class

Void main() { student s1,s2; s1.setdata(001,”rajesh”); s2.setdata(002,”shanker”); s1.putdata(); s2.putdata();}

Sathi Durga Devi, Department of IT,SNIST

Page 42: Unit v(dsc++)

Example on Member functions defined inside the class#include<iostream.h>• #include<string.h> class student { private:

int rollno;char name[30];

public:void setdata(int rn, char *n){

rollno=rn;strcpy(name, n);

{void putdata(){

cout<<“roll no=“<<rollno<<“\n”;cout<<“name=“<<name<<“\n”;

};Void main() { student s1,s2; s1.setdata(001,”rajesh”); s2.setdata(002,”shanker”); s1.putdata(); s2.putdata();}

Sathi Durga Devi, Department of IT,SNIST

roll no=001 name= rajesh roll no= 002 name= shanker

Page 43: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Class Scope: It tells in which parts of the program (or in which functions), the

class declaration can be used. Class scope may be local or global.

Local: If class is declared inside the function, then objects can be created

inside that function only.

Global: If class is declared outside the functions, then object can be created

in any function.

Page 44: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

#include<iostream.h>#include<conio.h>void print() {

class point{int a;public:void getdata() {cout<<"Enter an integer number: ";cin>>a;}void display() {cout<<"Entered number is: "<<a;}};point p;p.getdata();p.display();

}

void main(){ print(); }

//Example program for class inside a member function

Page 45: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

#include<iostream.h>#include<conio.h>class point{

int a;public:void getdata(){cout<<"\nEnter value of a :";cin>>a;}void display( ){cout<<"\nValue of a is: "<<a;}

};

void print() {point p;p.getdata();p.display();

}void main() {

clrscr();print();point m;m.getdata();m.display();getch();

}

//Example program for class outside a member function

Page 46: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Characteristics of member functions1. several classes in the same program may use the same member function. The ambiguity of the compiler in deciding which function belongs to which class

can be resolved by the scope resolution operator.2. Private member of a class can be accessed by all the members of the class. Whereas non member functions are not allowed to access.3. Member functions of the same class can access all the members of their own class without the dot operator.4. Private member function cannot invoke even with the object. ex- class test { int x;

void read(); public:

void display(); }t1 t1.read();// illegal

However, the function read() can be called by the function display void test :: display() { read();}//display()

Page 47: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Memory allocation for objects• The separate space is allocated for the objects when they are declared.• Memory is allocated for the functions when they are defined and no separate space

is allocated when the objects are created. That space is common for all the objects.• Separate space is allocated for the data members of the each object.

Member funciton1

Member function 2

Common for all the objects

Member variable1

Member variable 2

Member variable1

Member variable 2

Member variable1

Member variable 2

object1 object2 object3

Page 48: Unit v(dsc++)

class test{ int a,b; public: void display(int x,int y) { a=x; b=y; cout<<“a=“<<a’; cout<<“b=“<<b;}};

void main(){ test t; t.display(10,20); }

When object t created, it is not initializing the data members of class. It is performed by a call to the function display

Display function cannot initialize its members when the object created.

Sathi Durga Devi, Department of IT,SNIST

Page 49: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

constructors A constructor is a special member function whose task is to initialize the objects of its

class when they are created. This is also known as automatic initialization of objects. It is special because its name is the same as the class name The constructor is executed automatically whenever an object of its associated class is

created. It is called constructor because it constructs the values of data members of the class. The constructor is executed every time an object of that class is created.

Syntaxclass classname{

//private memberspublic:

classname(); //constructor declaration--------------------

};classname :: classname (void) //constructor definition {

}

The constructor is invoked automatically when the objects of that class are created . No need to write the special statement.

Page 50: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Characteristics of constructors Constructor name is same as class name. 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 and therefore,

they cannot return values. Constructor can access any data members but cannot be

invoked explicitly. They cannot be inherited, through a derived class can call the

base class constructor Like other , they can have default arguments They cannot refer to their address They make ‘implicit calls’ to the operators new and delete

when memory allocated or de allocation is required Note: when a constructor is declared for a class, initialization

of the class objects become mandatory

Page 51: Unit v(dsc++)

Example of constructor

Sathi Durga Devi, Department of IT,SNIST

void main(){ test t(10,20); test s(40,50); }

output a=10 b=20 a=40 b=50

Class test { int a,b; public: test(int x,int y); }; test::test(int x,int y){ a=x; b=y; cout<<“a=“<<a’; cout<<“b=“<<b; }

Page 52: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Types of Constructors:1) Default Constructor 2) Parameterized Constructor3) Copy Constructor

1. Default constructor: Constructor without parameters is called default constructor.

#include<iostream.h>class Test{

int a;public:

Test( ) { //Default constructora=1000;

} void display( ){

cout<<”a value is “<<a;}

};void main( ) {

Test t; //constructor is invoked after creation of object tt.display();

}

Page 53: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

2. Parameterized Constructor: Constructor which takes parameters is called Parameterized Constructor.

Example:#include<iostream.h>class Test{

public:Test(int x, int y)//// parameterized constructor

{ cout<<“x=“<<x<<“ y=“<<y<<endl;

};void main()

{Test t1(10,20); or Test(10,20);}

Page 54: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Constructor can also accepts the address of its own class as an argument. In such case the constructor is called copy constructor.

Copy constructor is a member function which is used to initialize an object from another object.

Copy Constructor is used to create an object that is a copy of an existing object.

By default, the compiler generates a copy constructor for each class.

3. Copy constructor

Syntax:class-name (class-name &variable){

-----;-----;

};

You can call or invoke copy constructor in the following way:class obj2(obj1);

orclass obj2 = obj1;

Page 55: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

#include<iostream.h>class point{ int a; public: point( ) //Default constructor { a=1000; } point(int x) //Parameterized constructor { a = x; } point(point &p) //Copy constructor { //p is an alternative name (alias) of

object p1 a = p.a; }void display( ) {

cout<<endl<<”a value is “<<a; } };

void main( ){point p1; point p2(500); point p3(p1); p1.display();p2.display();p3.display();}

Page 56: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

• We must pass some initial values as arguments to the constructor when an object is created.

• This can be done in two ways. 1. explicitly. 2. implicitly. 1. test t1= test(10,20);// explicitly 2. test t1(20,30);// implicit call.

Page 57: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

#include<iostream.h>Class integer{ int m,n; public: integer(int,int); void display( ) { cout<<“m=“<<m<<“\n”; cout<<“n=“<<n<<“\n”;}//display()};//class

Integer:: integer(int x,int y){ m=x; n=y;} main(){ integer I1(0,100); // constructor called implicitly integer I2= integer(10,20);// constructor called explicitly cout<<“\n object1”<<“\n”;I1.display();Cout<<“\nobject2”<<“\n”;I2.display(); return 0;}//main

Page 58: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

Destructor is a member function which is used to destroy an object when an object is no longer needed.

Destructor name is same as class name preceded by tilde mark (~). Destructor does not include return-type, not even void. Destructor does not return any value. Destructor cannot be overloaded. Single destructor is used in a class without arguments. Destructor is invoked when the object goes out of the scope. If no user-defined destructor exists for a class, the compiler implicitly

declares a destructor. Ex: class X

{ public:

X(); // Constructor for class X

~~X(); // Destructor for class X };

Destructor

Page 59: Unit v(dsc++)

Sathi Durga Devi, Department of IT,SNIST

include<iostream.h>class test{ public: test( ); //Default constructor ~ test();}; test:: test() { cout<<“\n constructor of a class”;} test :: ~test() { cout<<“\n destructor of a class”;}void main( ){ test T; //constructor is invoked after creation of object T cout<<“\n main(); }// object T goes out of the scope, destructor is called.