Untitled
unknown
c_cpp
10 months ago
2.4 kB
12
Indexable
oops :
class Teacher{
private:
string salary; //data hiding using encapsulation
public:
//default constructor
Teacher(){
dept="cs";
}
//parameterized constructor
Teacher(string n, string d){
name=n;
dept=d;
}
//copy constructor
Teacher(Teacher &obj){
this->name=obj.name;
this->dept=obj.dept;
}
//if we want the parameters to resemble the names of the attributes
//this keyword refers object's property
Teacher(string name, string dept){
name=name;
dept=dept; //very confusing for compiler
this->name=name;
this->dept=dept;//left prop is object prop
}
string name;
string dept;
void changeDept(string newdept){
dept=newdept;
}
//setter and getter methods to access private member variable - salary
void setSalary(int s){
salary = s;
}
int getSalary(){
return salary;
}
void getinfo(){
cout<<name<<endl;
cout<<dept<<endl;
}
};
//SHALLOW-DEEP COPY EXAMPLE
class Student{
public:
string name;
double* cgpaptr;
//parameterized constructor
Student(string n, double cgpa){
this->name=n;
cpaptr=new double();
*(cgpaptr)=cgpa;
}
//copy constructor - shallow copy / default copy constructor that will also be created by compiler if we dont create
Student(Student &obj){
this->name=obj.name;
cgpaptr = new double(); //re-allocation of dynamic memory
*cgpaptr=*(obj.cgpaptr); //value stored not address
}
//deep copy - custom copy constructor - mandatory
Student(Student &obj){
this->name=obj.name;
this->cgpaptr=obj.cgpaptr;
}
//destructor
~Student(){
//delete all dynamically allocated memory
delete cgpaptr; //avoid memory leak
}
};
int main(){
Teacher t1;
t1.name="x";
t1.dept="cs";
cout<<t1.salary<<endl; //not accessible as private
t1.setSalary(200);
cout<<t1.getSalary()<<endl; //acessible now
t1.getinfo();
//default copy constructor
Teacher t2(t1); //passing reference of object
t2.getinfo(); //works absolutely fine
//custom copy constructor
Teacher t3(t1);
t3.getinfo();
//shallow copy
Student s2(s1);
cout<<*(s1.cgpaptr)<<endl; //8.9
*(s2.cgpaptr)=9.2;
cout<<*(s1.cgpaptr)<<endl; //9.2
cout<<*(s2.cgpaptr)<<endl; //9.2
//we changed s2 but s1 also changed coz pointing to same address - shallow copy
//deep copy
Student s2(s1);
cout<<*(s1.cgpaptr)<<endl; //8.9
*(s2.cgpaptr)=9.2;
cout<<*(s1.cgpaptr)<<endl; //8.9
cout<<*(s2.cgpaptr)<<endl; //9.2
}Editor is loading...
Leave a Comment