Class Declaration
Access Control Specifiers
Instantiation of Objects
Constructor and Destructor
Examples
Structured Programming
FUNCTION FUNCTION
4 5
Data Data
Function Function
Object 3
Data
Function
Object
Class
A class is a user-defined data type from
which we can instantiate objects.
Class
A class encapsulates
data1
data and functions data2
data3
functiona()
functionb()
functionc()
class Cat
int main ()
{
{
public: Cat Kitty;
int Age; Kitty.Age = 5;
void Meow() Kitty.Meow();
{ cout << “meow…”; } return 0;
}; }
int main()
{
Counter c; //object instantiation
c.set(100);
while (c.get() != 0)
{ c.decrement();
c.show();
}
cout <<“Time out……!”<<endl;
return 0;
}
void print()
{ cout << “(” << x << “,” << y << “)”; }
};
int main()
{
Point p; //object instantiation
p.set(4,7); // member function call
p.print(); // member function call
}
Inline Functions
Class Definition
class Point
{
private:
int x, y;
public:
void set (int u, int v) // inline
{ x = u; y = v; }
void print(); // not inline, prototype
};
void Point::print() {
cout << “(“ << x << “,” << y << “)” << endl;
}
int main()
{
Point p; //object instantiation
p.set(4,7); // member function call
p.print(); // member function call
}
public:
Date() // default constructor
{ day = 1; month = 1; year = 2000;}
Date (int d, int m, int y); // parameterized constructor
void setYear(int y);
void setMonth(int m);
void setDay(int d);
void show(); // displays date
};
W03- Classes and Objects
27
Example:
class Date
{
public:
Date(); // constructor
~Date(); // destructor
…
};
Class Implementation
Date::Date (int d, int m, int y)
{
day=d;
month=m;
year = y;
}
void Date::show()
{
cout << day << ”-” << month << ”-” << year << endl;
}
W03- Classes and Objects
30
Instantiation of Objects
void main ()
{
Date d1 (14,8,1947);
Date d2 (17,2,2016);
Date d3;
Date d[10];
d1.show(); d2.show(); d3.show();
d[0] = d1; d[0].show();
}
W03- Classes and Objects
31