Classes and Objects
Classes and Objects
Chapter 2
Classes & Objects in OOP
Class in OOP
What is a class?
Example
Class in OOP: Destructors
What is a destructor? Destructor: C++ Program
class Test{
public:
Test(){
cout<<"Constructor is called"<<endl;
}
~Test(){
cout<<"Destructor is called"<<endl;
}
};
void CreateObj(){
Example Test t1,t2;
cout<<"Inside the CreateObj()"<<endl;
}
int main()
{
CreateObj();
return 0;
}
Class in OOP: Class in Different File
What is a destructor? reg.h
#include <iostream> class Circle{
#include "reg.h“ private:
int r;
using namespace std; public:
void SetRadius(int x){
int main(){ r=x;
Circle c1; }
c1.SetRadius(3); float GetArea(){
cout<<c1.GetArea(); return(3.14*r*r);
} }
};
Class in OOP: static Data Member
What is a static data member? // This program counts no. of objects
#include <iostream>
Static data members are class members that are declared using namespace std;
using static keywords. A static member has certain class Base{
special characteristics which are as follows: int x;
static int y;
• Only one copy of that member is created for the public:
entire class and is shared by all the objects of that Base(int X){
class, no matter how many objects are created. x=X;
• It is initialized before any object of this class is y++;
created, even before the main starts. }
• It is visible only within the class, but its lifetime is the static int getY(){ return y;}
entire program. };
• The value must be initialized outside the class int Base::y=0;
• The getter function must be static int main()
Syntax: {
Base c1(10),c2(20);
static data_type data_member_name; cout<<Base::getY();
return 0;
}
Class in OOP: Passing Object as Parameter
Example Contd..
#include <iostream> int main()
using namespace std; {
Ball b1(130),b2(140);
class Ball{
b1.AvgSpeed(&b2);
private:
int s; return 0;
public: }
Ball(){}
Ball(int x){ b
s=x;
} s=130 s=140
void AvgSpeed(Ball *b){
cout<<(s+b->s)/2;
}
};
b1 b2
Class in OOP: Object as Function Return
Example Contd..
#include <iostream> int main()
using namespace std; {
class Ball{ Ball b1(130),b2(140);
private: Ball k;
float s; k=b1.AvgSpeed(&b2);
public: cout<<k.GetSpeed()/2;
Ball(){} return 0;
Ball(int x){ }
s=x;
}
float GetSpeed (){ s=130 s=140 s=170 s=170
return s;
}
Ball AvgSpeed(Ball *b){
Ball t;
t.s=s+b->s; b1 b2 t k
return(t); b
}
};
Class in OOP: Copy Constructor
What is a Copy Constructor?
A copy constructor is a member function that initializes an object using another object of the same
class. In simple terms, a constructor which creates an object by initializing it with an object of the same
class, which has been created previously is known as a copy constructor.
Copy constructor is used to initialize the members of a newly created object by copying the members of
an already existing object.
};
End