Professional Documents
Culture Documents
Object Oriented Programming: Lecture 4: Classes and Objects
Object Oriented Programming: Lecture 4: Classes and Objects
Engineer’s View
Driver’s View
#include <iostream>
using namespace std; void MultiplyByTwo()
class Shape //define a class {
{ int mul;
private: mul = length * length;
int length; //class data }
public: int main()
void setlength(int l) //member function to set data {
{ Shape line;
length = l; // set line length
} line.setlength(6.0);
int showlength() //member function to display data cout << "Length of line : "<< line.showlength();
{ return 0;
return length; }
}
}
Object oriented programming in C++ by Robert Lafore 13
Object oriented programming in C++ by Robert Lafore 14
class Distance
{
private:
int feet;
float inches;
int main()
public: {
void setdist(int ft, float in) Distance dist1;
{ dist1.setdist(11, 6.25); //set dist1
feet = ft; inches = in; dist2.getdist(); //get dist2 from user
} return 0;
void getdist() }
{
cout << “\nEnter feet: “; cin >> feet;
cout << “Enter inches: “; cin >> inches;
}
void showdist() //display distance
{ cout << feet << “\’-” << inches << ‘\”’; }
};
dist1.showdist();
dist2.showdist();
cout << endl;
return 0;
}
dist1.showdist();
dist2.showdist();
dist3.showdist();
cout << endl;
return 0;
}
}
void display()
{
cout<<“Age"<<*Age<<endl;
}
~Human()
{
delete age;
cout<<"Released all memories"<<endl;
}
};
Object oriented programming in C++ by Robert Lafore 26
class sampleclass
{
sampleclass* ptr; // this is fine
};
However, while a class can contain a pointer to an object of its own type, it cannot
contain an object of its own type:
class sampleclass
{
sampleclass obj; // can’t do this
};
int main()
{
Int *arr_ptr [3];
Int x=0,y=1,z=3;
arr_ptr[0]=&x;
arr_ptr[1]=&y;
arr_ptr[2]=&z;
return 0;
}