Professional Documents
Culture Documents
TASTE OF C++
March 29 2016
Outline
• The components of “class” in C++
• Variables and Methods
• Creator and Destructor of a Class
• Inheritance
Class
• The class in C++ is very similar to, but more extended from the structure in C.
• Any class has variables and methods as its members.
• There are access specifier for the members.
class Quadrangle
{
private: Access specifier
int width;
int height; Members
int area;
public : Access specifier
int CalcuateArea ( int argWidth, int argHeight)
{
width = argWidth; Method
height = argHeight;
area = width * height;
return area;
};
};
Example of using Class
#include <iostream>
class Fish
{
public:
void Swim()
{
printf("You invoke swim()\n");
};
};
int main()
{
Fish fish;
fish.Swim();
}
‘.’ pperator is used in the same way as in the structure of C-language
Access Specifier
• private members of a class are accessible only by other members (methods) of the
same class
• protected members are accessible from other members of the same class, but also
from members of their derived (inheriting) classes.
• public members are accessible from anywhere where the object is visible.
Example
class Quadrangle
{ int main()
private: {
int width; Quadrangle A;
int height; A.width=3; // Error
int area; A.CalcuateArea(3, 2); // O.K
}
public:
int CalcuateArea ( int argWidth, int argHeight);
};
int GetDefense();
};
Parent class Child class
Sample float TriangleArea::Calculate()
{
#include <iostream> float area = 0 ;
class TriangleArea area = width * height;
{ area = area / 2.0;
private:
int width;
int height; return area;
}
public:
TriangleArea(int argWidth, int argHeight); void main()
float Calculate(); {
}; int width = 0, height = 0;
TriangleArea::TriangleArea(int argWidth, int argHeight) cout << ”Width= ”; cin >> width;
{ cout << ”height= ”; cin >> height;
width = argWidth;
height = argHeight;
} TriangleArea* triArea =
new TriangleArea(width, height);
cout << ”The ares is " <<
triArea->Calculate() <<
“square centimeter”<< endl;
}
Exercise
Exercise 1
Make C++ program, which prints out “Hello World”. The printf function should be
called as a ‘method’ of a class.
Homework
Question 1
Make a C++ program, which gets two float numbers from the command line, and
calculate the product of them.
Question 2
Extend your code using ‘inheritance’, from which a sum of the two numbers is
calculated.