Title: Plab Tirgul 6 Classes
1Plab Tirgul 6Classes
2Point.h
class Point public Point(int x, int
y) Point() int getX() const int
getY() constprivate int m_x, m_y
3Circle.h
include "Point.h class Circle public
Circle(int x, int y, double r)
Circle() // ... private Point
m_center // ...
4Circle.cpp
include "Circle.h CircleCircle(int x, int y,
double r) m_center(x,y) // ...
CircleCircle() printf(in
Circle()")
Wont compile without
5- The same syntax also works for base
types.PointPoint(int x, int y) m_x(x) ,
m_y(y) is better than - PointPoint(int x, int y) m_x x
m_y y
6Inheritance
- The main ideas are similar to what you already
know from Java. - C has no interfaces but it allows multiple
inheritance - For now we will not discuss the problems that
arise
Class A
Class C
Class B
Class D
7Circle class - again
include "Point.h class Circle Point public
Circle(int x, int y, double r)
Circle() // ...
private // ...
include "Circle.h CircleCircle(int x, int y,
double r) Point(x,y) // ...
CircleCircle() printf(in
Circle()")
Wont compile without
8Default arguments in constructors
- In C
- PointPoint(int x 0, int y 0) //
... - is equivalent to JavasPoint(int x, int y) . .
.Point(int x) this(x,0) Point()
this(0,0) - Note that now Point has a default constructor!
Nothing similar in C
9C-tor D-tor order of execution
- Constructor of the base class is the 1st to be
executed. - Then the members are constructed.
- Finally, the constructor of the class itself is
executed. - Destruction is done in the opposite order.
10protected
- Class members that should be accessible by
subclasses are declared protected. - Example to allow Circle access coordinates of
Point we would define
class Point public // . . . protected
int m_x, m_y
11this
- A (constant) pointer to the instance for which
the member function was invoked. - Example
class List List nextpublic bool
on(List) // ...
bool Liston(List p) if (pnull)
return false for (List q this q
qq-gtnext) if (q p) return true
return false
12inline functions
- A hint to a compiler to put functions code
inline, rather than perform a regular function
call. - Objective improve performance of small,
frequently used functions. - Example allocateNode() function in data
structures like Linked List or Binary Tree. - A member function defined in class definition
(i.e. the header file) is automatically
considered to be inline. - An inline function defined in .cpp file is not
recognized in other source files.
13Static class members
- As in Java, these are members belonging to the
class rather than to an instance.
class X private static int instances
public X() instances X()
instances-- static int getInstances()
return instances
X.h
14Static class members
Somewhere (but only in one place!) the instances
variable should be defined int Xinstances 0
In Java declaration and defintion were in the
same place
Example of using a static function X x1 //
... X x2 // ... printf(d\n,
XgetInstances())