Beruflich Dokumente
Kultur Dokumente
Classes in C++
Member access specifiers
public:
private:
class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
void main()
Circle::Circle(int r)
{
{
Circle c(7);
radius = r;
Circle *cp1 = &c;
}
Circle *cp2 = new Circle(7);
double Circle::getArea()
cout<<The are of cp2:
{
<<cp2->getArea();
return radius * radius * (22.0/7);
}
double Circle:: getCircumference() }
{
return 2 * radius * (22.0/7);
}
Destructor
class Time
{
private:
int *hour,*minute,*second;
public:
Time();
Time(int h,int m,int s);
void printTime();
void setTime(int h,int m,int s);
int getHour(){return *hour;}
int getMinute(){return *minute;}
int getSecond(){return *second;}
void setHour(int h){*hour = h;}
void setMinute(int m){*minute = m;}
void setSecond(int s){*second = s;}
~Time();
};
Time::Time()
{
hour = new int;
minute = new int;
second = new int;
*hour = *minute = *second = 0;
}
Dynamic locations
should be allocated
to pointers first
void Time::printTime()
{
cout<<"The time is : ("<<*hour<<":"<<*minute<<":"<<*second<<")"
<<endl;
}
Time::~Time()
{
delete hour; delete minute;delete second;
}
void main()
{
Time *t;
t= new Time(3,55,54);
t->printTime();
Output:
The time is : (3:55:54)
The time is : (7:17:43)
Press any key to continue
t->setHour(7);
t->setMinute(17);
t->setSecond(43);
t->printTime();
delete t;
}
3. Software reuse
Modules
?Why OO-Programming
Keys to OO Programming
Keys to OO Programming
Inheritance
Enable a new abstraction (i.e., derived class) to be
defined as an extension of an existing abstraction,
retaining key characteristics
Classes in C++
A class definition begins with the keyword
class.
The body of the class is contained within a
set of braces, { } ; (notice the semi-colon).
class class_name
}
.
.
.
;{
Any valid
identifier
Class body (data member
+ methods)
methods
++Classes in C
Within the body, the keywords private: and
public: specify the access level of the
members of the class.
the default is private.
Classes in C++
class class_name
}
:private
public:
;{
private members or
methods
Class Example
This class example shows how we can
encapsulate (gather) a circle information
into one package (unit or class)
No need for others classes to
class Circle
{
private:
double radius;
public:
void setRadius(double r);
double getDiameter();
double getArea();
double getCircumference();
};
Constructor with no
argument
Constructor with one
argument
Defined
inside
class
class Circle
{
private:
double radius;
public:
Circle() { radius = 0.0;}
Circle(int r);
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
double getCircumference();
};
Circle::Circle(int r)
{
radius = r;
}
double Circle::getArea()
{
return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}
class Circle
{
private:
double radius;
public:
The first
The second
Circle() { radius = 0.0;}
constructor is
constructor is
Circle(int r);
called
called
void setRadius(double r){radius = r;}
double getDiameter(){ return radius *2;}
double getArea();
Since radius is a
void main()
double getCircumference();
private class data
{
};
Circle c1,c2(7);
member
Circle::Circle(int r)
{
cout<<The area of c1:
<<c1.getArea()<<\n;
radius = r;
}
//c1.raduis = 5;//syntax error
double Circle::getArea()
c1.setRadius(5);
{
return radius * radius * (22.0/7);
cout<<The circumference of c1:
}
<< c1.getCircumference()<<\n;
double Circle:: getCircumference()
{
cout<<The Diameter of c2:
<<c2.getDiameter()<<\n;
return 2 * radius * (22.0/7);
}
}
Classes
Extends the scope rules of modules to
.include inheritance
Should private members of a base class be
?visible in derived classes
Should public members of a base class
always be public members of a derived
.class
How much control should a base class
?have over its members in derived classes
C++ Classes
Any class can limit the visibility of its
:members
Public members are visible anywhere the class
.is in scope
Private members are visible only within the
.classs methods
Protected members are visible inside members
.of the class and derived classes
Friend classes are granted exceptions to
.(some) of the rules
C++ Classes
Derived classes can further restrict visibility of
:base class members, but not increase it
Private members of a base class are never visible in a
.derived class
Protected and public members of a public base class
.are protected or public, respectively, in a derived class
Protected and public members of a protected base
.class are protected members of a derived class
Protected and public members of a private base class
.are private members of a derived class
C++ Classes
Derived classes that limit visibility of base class
members can restore visibility by inserting a
using declaration in its protected or public
.sections
Rules in other languages can be significantly
.different
Member Lookup
Inheritance
Encapsulation
:Encapsulation Requires that functions, modules and classes
Have clearly defined external interfaces
Hide implementation details
public functions
private
functions
private data
Figure 3.1
Isolated tasks: the implementation of task T does not affect task Q
Implementation of an ADT
Includes choosing a particular data structure
Figure 3.4
A wall of ADT operations isolates a data structure from the program that uses it
Figure 3.7
The wall between displayList and the implementation of the ADT list
Designing an ADT
The design of an ADT should evolve
naturally during the problem-solving process
Questions to ask when designing an ADT
?What data does a problem require
?What operations does a problem require
Designing an ADT
For complex abstract data types, the
behavior of the operations must be specified
using axioms
Axiom: A mathematical rule
Ex. : (aList.createList()).size() = 0
Implementing ADTs
Choosing the data structure to represent the
ADTs data is a part of implementation
Choice of a data structure depends on
Details of the ADTs operations
Context in which the operations will be used
Implementing ADTs
Implementation details should be hidden
behind a wall of ADT operations
A program would only be able to access the
data structure using the ADT operations
Implementing ADTs
Figure 3.8
ADT operations provide access to a data structure
Implementing ADTs
C++ Classes
Encapsulation combines an ADTs data with
its operations to form an object
An object is an instance of a class
A class contains data members and member
functions
Inheritance Concept
{class Rectangle
Polygon
Rectangle
Triangle
:private
;int numVertices
;float *xCoord, *yCoord
:public
;void set(float *x, float *y, int nV)
();float area
;{
{class Polygon
:private
;int numVertices
;float *xCoord, *yCoord
:public
;void set(float *x, float *y, int nV)
;{
{class Triangle
:private
;int numVertices
;float *xCoord, *yCoord
:public
;void set(float *x, float *y, int nV)
();float area
;{
Inheritance Concept
Polygon
Rectangle
Triangle
{class Polygon
:protected
;int numVertices
;float *xCoord, float *yCoord
:public
;void set(float *x, float *y, int nV)
;{
{class Rectangle
:protected
;int numVertices
;float *xCoord, float *yCoord
:public
;void set(float *x, float *y, int nV)
();float area
;{
Inheritance Concept
Polygon
Rectangle
Triangle
{class Polygon
:protected
;int numVertices
;float *xCoord, float *yCoord
:public
;void set(float *x, float *y, int nV)
;{
{class Triangle
:protected
;int numVertices
;float *xCoord, float *yCoord
:public
;void set(float *x, float *y, int nV)
();float area
;{
Inheritance Concept
x
y
Point
Circle
3D-Point
x
y
r
x
y
z
{class Point
:protected
;int x, y
:public
;void set (int a, int b)
;{
Inheritance Concept
Augmenting the original class
Polygon
Rectangle
Point
Circle
Triangle
3D-Point
real
RealNumber
real
imag
ImaginaryNumber
imag
?Why Inheritance
Inheritance is a mechanism for
building class types from existing class types
defining new class types to be a
specialization
augmentation
of existing types
Class Derivation
Point
3D-Point
Sphere
{class 3D-Point : public Point
: private
;double z
;{
{class Point
:protected
;int x, y
:public
;void set (int a, int b)
;{
{class Sphere : public 3D-Point
: private
;double r
;{
Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
?What to inherit
In principle, every member of a base class
is inherited by a derived class
just with different access permission
members goes to
derive from
b a s e c la s s / s u p e r c la s s /
p a r e n t c la s s
d e r iv e d c la s s / s u b c la s s /
c h ild c la s s
;{
Access Control
for Members
private
protecte
d
private
-
protected
-
public
-
private
protected protected
public
private
protected
public
The type of inheritance defines the access level for the
members of derived class that are inherited from the
base class
Public Inheritance
class A : public B
Class A now inherits the members of Class // {
B
with no change in the access specifier for //
the inherited members// }
Protected Inheritance
class A : protected B
Class A now inherits the members of Class B// {
with public members promoted to protected//
but no other changes to the inherited // }
members
Private Inheritance
class A : private B
Class A now inherits the members of Class B // {
with public and protected members//
promoted to private// }
private base class (B)
public members
protected members
private members
Class Derivation
{class mother
;protected: int mProc
;public: int mPubl
;private: int mPriv
;{
private/protected/public
{class daughter : --------- mother
;private: double dPriv
((););public:
public:void
voidmFoo
dFoo
;{
() {int main
/*.*/
{
?What to inherit
In principle, every member of a base
class is inherited by a derived class
just with different access permission
Inheritance (continued)
class Shape
}
:public
( ) ; int GetColor
so derived classes can access it//
:protected
;int color
;{
class Two_D : public Shape
}
put members specific to 2D shapes here//
;{
class Three_D : public Shape
}
put members specific to 3D shapes here//
;{
Inheritance (continued)
class Square : public Two_D
}
:public
( ) ; float getArea
:protected
;float edge_length
;{
class Cube : public Three_D
}
:public
( ) ; float getVolume
:protected
;float edge_length
;{
Inheritance (continued)
( ) int main
}
;Square mySquare
;Cube myCube
Square inherits //
( ); mySquare.getColor
( ); mySquare.getArea
)(Cube inherits getColor //
( ); myCube.getColor
( ); myCube.getVolume
{
Point
x
y
r
x
y
Circle
{class Circle : public Point
: private
;double r
:public
;void set_r(double c)
;{
{class Point
:protected
;int x, y
:public
;void set(int a, int b)
;{
{class Circle
:protected
;int x, y
:private
;double r
:public
;void set(int a, int b)
;void set_r(double c)
;{
Even more
A derived class can override methods defined in its
,parent class. With overriding
the method in the subclass has the identical signature to the
. method in the base class
. a subclass implements its own version of a base class method
{class A
:protected
;int x, y
:public
()void print
;}cout<<From A<<endl{
;{
{class B : public A
: public
()void print
;}cout<<From B<<endl {
;{
Access a Method
{class Point
:protected
;int x, y
:public
void set(int a, int b)
;}x=a; y=b{
();void foo
();void print
;{
;Point A
A.set(30,50); // from base class Point
A.print(); // from base class Point
;Circle C
C.set(10,10,100); // from class Circle
C.foo (); // from base class Point
C.print(); // from class Circle
ExtTime
POLYMORPHISM
Polymorphism:Definition
Types of polymorphism
Primitively divided into two types
polymorphism
Compile-time
polymorphism
Function Overloading
Operator overloading
Run-time
polymorphism
Virtual functions
Run-time polymorphism
Binding of Function call and function
definition is done during Run time. This is
.known as late or dynamic binding
If late binding happens in polymorphism it is
known as run-time polymorphism
C++ supports a mechanism known as
virtual functions to achieve run-time
.polymorphism
:Example
Class person
}
;char name[30]
;float age
:public
person)char *s,float a(
}
;strcpy)name,s(
;age=a
{
person& greater)person &x(
}
if)x.age>=age(
;return x
else
;return *this
{
void display )void(
}
;cout<<name<<age
{
;{
Abstract Classes
An abstract class represents an abstract concept in C++ (such
as Shape class)
Shape
Circle
Polygon
Rectangle
()int main
}
;Person P1(john,32)
;Person P2(ahmed,38)
;Person P3(karthik,30)
;Person p=P1.greater(P2)
;cout <<elder person
();p.display
;p=P3.greater(P2)
;cout<<younger person
();p.display
{
Abstract Classes
An abstract class represents an abstract concept in C++ (such
as Shape class)
Shape
Circle
Polygon
Rectangle
Function Overloading
C++ supports writing more than one function
with the same name but different argument
:lists. This could include
different data types
different number of arguments
Function Overloading
Function Overloading
void swap (int *a, int *b)
; }int temp; temp = *a; *a = *b; *b = temp{
void swap (float *c, float *d)
} ;float temp; temp = *c; *c = *d; *d = temp {
void swap (char *p, char *q)
} ;char temp; temp = *p; *p = *q; *q = temp {
Friends
Basically, when you declare something as a friend,
.you give it access to your private data members
This is useful for a lot of things for very
interrelated classes, it more efficient (faster) than
using tons of get/set member function calls, and
they increase encapsulation by allowing more
.freedom is design options
Friends
A class doesn't control the scope of friend
functions so friend function declarations are
usually written at the beginning of a .h file. Public
. and private don't apply to them
Friends
{class someClass
;friend void setX( someClass&, int)
;int someNumber
}rest of class definition
a function called setX defined in a program //
{void setX( someClass &c, int val)
; }c.someNumber = val
inside a main function//
;someClass myClass
//this will work, since we declared setX (myClass, 5);
// setX as a friend
ass Declarations
n be declared within the scope of another clas
ass." Nested classes are considered to be with
class and are available for use within that scop
a scope other than its immediate enclosing sc
name
value class Outside { value class Inside { }; }; In the same way, you can
nest as many classes as you wish in another class and you can nest
as many classes inside of other nested classes if you judge it
necessary. Just as you would manage any other class so can you
exercise control on a nested class. For example, you can declare all
necessary variables or methods in the nested class or in the nesting
class. When you create one class inside of another, there is no special
programmatic relationship between both classes: just because a class
is nested doesn't mean that the nested class has immediate access to
the members of the nesting class. They are two different classes and
. they can be used separately
The name of a nested class is not "visible" outside of the nesting class.
To access a nested class outside of the nesting class, you must qualify
the name of the nested class anywhere you want to use it. This is done
using the :: operator. For example, if you want to declare an Inside
variable somewhere in the program but outside of Outside, you must
:qualify its name. Here is an example
{
value class CInside
}