Presentation is loading. Please wait.

Presentation is loading. Please wait.

OBJECT ORIENTED PROGRAMMING LECTURE 7 Instructor: Rashi Garg Coordinator: Gaurav Saxena.

Similar presentations


Presentation on theme: "OBJECT ORIENTED PROGRAMMING LECTURE 7 Instructor: Rashi Garg Coordinator: Gaurav Saxena."— Presentation transcript:

1 OBJECT ORIENTED PROGRAMMING LECTURE 7 Instructor: Rashi Garg Coordinator: Gaurav Saxena

2 Tips !!! 1. A constructor with a default arguments is equivalent to a default constructor. class A { int i; float j; public: A(int a=0, float b=1000.0); // Constructor Definition }; A::A(int a,float b) { i=a; j=b; } int main() { A obj1(23,2715.50); // Valid A obj2; //Valid }

3 Contd … 2. Default constructor are useful when:  Want to create objects without having to type initial values  Want to initialize objects every time with prespecified initial values.  If you want to create array of objects

4 Output of Code Below ??? class Test { int a; char b; public: Test() { cout<<“Default Constructor”; } Test(int i, char j) { a=i; b=j; cout<<“Parameterized Constructor”; } }; int main() { Test Tarray[5]; Test newobj(31,’z’); } Output: Default Constructor Parameterized Constructor

5 Question ? Can you create an array of objects if the default constructor of the class is private YES. Array of objects can still be created but only inside the member function of the class as only member function have access to default constructor. Array of such objects cannot be created inside non member function.

6 Copy Constructor Is the constructor of the form classname(classname &). Compiler will use copy constructor whenever you want to initialize an instance using values of another instance of same type.

7 Contd … Sample s1; //Default constructor Sample s2=s1; //Copy Constructor used Compiler will copy the instance s1 to s2 member by member. If copy constructor is not defined compiler automatically creates it and it is public.

8 How to define Copy Constructor ? Copy Constructor takes a reference to an object of the same class as argument. class Sample { int i,j; public: Sample(int a,int b) { i=a; j=b; } Sample(Sample & s) { i=s.i; j=s.j; cout<<“Copy Constructor”; } void print() { cout<<i<<j; } }; Sample s1(4,10); //1st Constructor used Sample s2=s1; //s1 copied to s2 Sample s3=s1; //s1 copied to s3 Sample s4; s4=s1; //s1 copied to s4 using default copy constructor

9 Contd … Process of initializing through a copy constructor is known as copy initialization.

10 When is Copy Constructor called??? There are 2 situations when a copy constructor is invoked: ▫When a object is passed by value ▫When a function returns object

11 Object passed as Value Copy constructor is invoked when an object is passed by value to a function. Pass by value method requires a copy of the passed argument to be created for the function to operate upon. void afunc(Sample); //Sample is a class afunc(obj1); //obj1 is a object of Sample type Copy constructor would be invoked to create a copy of obj1 for use by afunc(). In Pass by reference no copy is created thus copy constructor is not invoked.

12 Returning Objects class complex { float x; float y; public: void input(float real,float imag) { x=real; y=imag; } friend complex sum(complex, complex); void show(complex); }; complex sum(complex c1,complex c2) { complex c3; c3.x=c1.x+c2.x; c3.y=c1.y+c2.y; return(c3); } void complex::show(complex c) { cout<<c.x<<c.y; } int main() { complex A,B,C; A.input(3.1,5.65); B.input(2.75,1.2); C=sum(A,B); cout<<A.show(A); cout<<B.show(B); cout<<C.show(C); }

13 When function returns an object When a function with following prototype: Sample afunc(); //Sample is a class and it is return type of afunc() Sample obj2; obj2=afunc(); Copy constructor would be invoked to create a copy of value returned by afunc() and this value would be assigned to obj2. Copy constructor creates a temporary object to hold the return value of a function returning an object.

14 Why argument passed by reference in Copy Constructor ??? If we try to pass argument by value to a copy constructor i.e. if we use X(X) in place of X(X &) Compiler complains out of memory WHY ??? To create a copy of object who works ??? Copy Constructor. The copy constructor is creating copy of object for itself, thus it calls itself. Again called copy constructor requires another copy so again it is called. It calls itself again and again until compiler runs out of memory. So argument must be passed by reference so that to make copy of passed object, original object is directly available

15 Example #include using namespace std; class code { int id; public: code(){} code(int a){id=a;} code(code &x) { id=x.id; } void display() { cout<<id; } }; int main() { code A(100); code B(A); code C=A; code D; D=A; cout<<A.display(); cout<<B.display(); cout<<C.display(); cout<<D.display(); return 0; }

16 Order of Constructor Invocation Everytime an object is created the constructor of its class is automatically invoked. When there are multiple objects being declared simultaneously in such a case can you determine the order of constructor invocation??? There is no need to determine it, there is a predefined order of constructor invocation Objects are constructed in the order they are defined. ▫Sample s1,s2,s3;

17 Contd … Consider a class containing objects of another class as its members. Constructors of member objects are invoked first and then only constructor for the containing class is invoked.

18 Example class Subject { int days; int subjectno; public: Subject(); void prinsub() { cout<<subjectno; cout<<days; } }; Subject::Subject() { cout<<“Constructing Subject”; days=0; subjectno=0; } class Student { Subject sub; int rollno; float marks; public: Student() { cout<<“Constructing Student”; rollno=0; marks=0.0;} void getval() {cin>>rollno>>marks} void printval() {cout<<rollno<<marks} }; int main() { clrscr(); Student stud; cout<<“Back in main()”; return 0; }

19 Output Constructing Subject Constructing Student Back in main()

20 Can we initialize const and reference If class contains const and/or reference as member field then traditional way of initializing members will not work. struct Sname { char fname[25]; //cannot initialize here char lname[25]; //cannot initialize here }s1; class Test { int a,b; const int max; Sname & name; public: Test() { a=0; b=10; max=300; //Error name=s1; //Error } }; int main() { Test obj1; }

21 Member Initialization List A constructor can initialize the constituents data members of its class through a mem-initialization list that appears in the function header of constructor class Test { int a; char b; public: Test(int i,char j) { a=i; b=j; } }; class Test { int a; char b; public: Test(int i,char j): a(i), b(j) { } }; class Test { int a; char b; public: Test(int i,char j): a(i) {b=j; } };

22 Contd … If class contains a const and/or reference member then these members must be initialized within constructor body. struct Sname { char fname[25]; //cannot initialize here char lname[25]; //cannot initialize here }s1; class Test { int a,b; const int max; Sname & name; public: Test() : max(300), name(s1) { a=0; b=10; } }; int main() { Test obj1; }

23 Where to use Mem-Initialization List ? Initialization of const members Initialization of reference members Invoking base class constructor (Inheritance) Initialization of member objects (Inheritance)

24 Constructor Overloading Constructor of the class may also be overloaded so that even with different number and types of initial values an object may still be initialized.

25 Example class Deposit { long int principal; int time; float rate; float total_amnt; public: Deposit(); Deposit(long p,int t,float r); Deposit(long p,int t); Deposit(long p,float r); }; Deposit::Deposit() {principal=time=rate=0;} Deposit::Deposit(long p,int i,float r) {principal=p; time=t; rate=r;} Deposit::Deposit(long p,int t) {principal=p; time=t; rate=0.08;} Deposit::Deposit(long p, float r) {principal=p; time=2; rate=r;} void main() { Deposit D1; Deposit D2(2000,2,0.07f); Deposit D3(4000,1); Deposit D4(3000,0.12f); }

26 Special Characteristics of Constructors Constructor functions are invoked automatically when the objects are created. If a class has a constructor each object of that class will be initialized before any use is made of object. Constructor function obeys the usual access rules. That is private and protected constructors are available only for member and friend functions however public constructors are available for all the functions. No return type (not even void) can be specified for a constructor. They cannot be inherited though derived class can call the base class constructor.

27 Contd … A constructor may not be static. Default and copy constructors are generated where needed. Generated constructors are public. Constructors can have default arguments. An object of class with constructor cannot be member of union. Member function may be called from within a constructor A constructor can be called explicitly to create new objects of its class type

28 Destructor If a class can have a constructor to set things up, it should have a destructor to destruct object Destructor destroys the object that have been created by constructor. Destructor destroys the value of object being destroyed. Destructor is a member function whose name is same as that of class name preceded by tilde (~). ▫Destructor for Sample class: ~Sample()

29 Contd … Destructor takes no arguments and no return types can be specified for it (not even void). It is called automatically by the compiler when an object is destroyed. A destructor cleans up the storage (memory area of the object) that is no longer accessible. ~classname()  Syntax of destructor

30 Example class Sample { int i,j; public: Sample(int a, int b) { i=a; j=b; } ~Sample() { cout<<“Destructor at work”; } }; int main() { Sample s1(3,4); : //automatically s1 is destructed at the end of the block using destructor ~Sample() }

31 Need for Destructor During construction of an object by the constructor, resources may be allocated for use. ▫Constructor may have opened a file and a memory area may be allotted to it. ▫Constructor may have allocated memory to some other objects The allocated resources must be deallocated before the object is destroyed. A destructor volunteers here for this task and performs all clean-up task.

32 Declaration and Definition Destructor declared like any other member function. It does not take any argument neither does it return any value. A destructor being a member function obeys the usual access rules for a member function If defined as private or protected member function it becomes available only for member or friend function If a class defines a public destructor its objects can be created, used, and destroyed by any function.

33 Example class Sample { int i; int j; ~Sample() { cout<<“Destructing”; } public: Sample(){i=0;j=0;} void memb1(); }; void Sample::memb1() { Sample s1; : } int main() { Sample s2; : }

34 Contd … If you fail to define a destructor for a class the compiler will automatically generates one,the default destructor. If more than one object is being destructed, the destructors are invoked in the reverse order in which the constructors were called. Sample s1; //s1 Constructed Sample s2; //s2 Constructed Sample s3; //s3 Constructed : Sample s3; //s3 destructed Sample s2; //s2 destructed Sample s1; //s1 destructed

35 Some characteristics of Destructor Destructor function are invoked automatically when the objects are destroyed. If a class has a destructor each object of that class will be deinitialized before the object goes out of scope Destructor function obeys the usual access rules No argument can be provided to a destructor neither does it return any value They cannot be inherited A destructor may not be static It is not possible to take the address of a destructor

36 Contd … Member function may be called from within the destructor An object of a class with a destructor cannot be a member of a union


Download ppt "OBJECT ORIENTED PROGRAMMING LECTURE 7 Instructor: Rashi Garg Coordinator: Gaurav Saxena."

Similar presentations


Ads by Google