Object-Oriented Programming
Introduction to Classes
• Class Introduction & definition
• Difference between Class & Struct
• Data Members
• Static Data Members
• Member Functions & definition
• Constant member Functions
• Access Control
• Class interface Diagram
• Object, its declaration and initialization
• Constructor
• Destructor
1
Class
• The class is the cornerstone of C++
– It makes possible encapsulation, data hiding and inheritance
• Type
– Concrete representation of a concept
• Eg. float with operations like -, *, + (math real numbers)
• Class
– A user defined type
– Consists of both data and methods
– Defines properties and behavior of that type
• Advantages
– Types matching program concepts
• Game Program (Explosion type)
– Concise program
– Code analysis easy
– Compiler can detect illegal uses of types
• Data Abstraction
– Separate the implementation details from its essential properties
2
Structure vs Class
• In C++, a structure is the same as a class
except for a few differences.
• A Structure is not secure and cannot hide
its implementation details from the end
user while a class is secure and can hide
its programming and designing details.
3
1) Members of a class
are private by default
and members of a
struct are public by
default.
For example program 1
fails in compilation and
program 2 works fine.
4
2) When deriving a
struct from a
class/struct, default
access-specifier for a
base class/struct is
public. And when
deriving a class, default
access specifier is
private.
For example program 3
fails in compilation and
program 4 works fine.
5
Classes & Objects
Objects: Instance of a class
class Rectangle
{
Rectangle r1;
private: Rectangle r2;
int width; Rectangle r3;
int length;
……
public:
void set(int w, int
l);
int a;
int area();
};
6
Define a Class Type
Header class Rectangle
class class_name {
{ private:
permission_label:
int width;
member;
int length;
Body permission_label:
member; public:
... void set(int w, int
}; l);
int area();
}; 7
Class Definition
Data Members
• Can be of any type, built-in or user-defined
• non-static data member
– Each class object has its own copy
• static data member
– Acts as a global variable
– One copy per class type, e.g. counter
8
Static Data Member
Rectangle r1;
class Rectangle Rectangle r2;
{ Rectangle r3;
private:
int width;
int length; count
static int count;
r1 r2
public: width width
void set(int w, int length length
l); width
int area(); r3 length
9
}
Class Definition
Member Functions
• Used to
– access the values of the data members (accessor)
– perform operations on the data members
(implementor)
• Are declared inside the class body
• Their definition can be placed inside the class
body, or outside the class body
• Can access both public and private members of
the class
• Can be referred to using dot or arrow member
access operator
10
Define a Member Function
class Rectangle
{
private:
int width, length;
class name
public:
void set (int w, int l);
int area() {return width*length; } member function name
};
void Rectangle :: set (int w, int l)
inline {
r1.set(5,8);
width = w;
rp->set(8,10); length = l;
} scope operator
11
Class Definition
Member Functions
• const member function
– declaration
• return_type func_name (para_list) const;
– definition
• return_type func_name (para_list) const { … }
• return_type class_name :: func_name (para_list) const { … }
– Makes no modification about the data members (safe
function)
– It is illegal for a const member function to modify a
class data member
12
Const Member Function
class Time
{
private : function declaration
int hrs, mins, secs ;
public :
void Write ( ) function definition
const ;
};
void Time :: Write( ) const
{
cout <<hrs << “:” << mins << “:” << secs << endl;
}
13
Class Definition - Access Control
• Information hiding
– To prevent the internal representation from direct
access from outside the class
• Access Specifiers
– public
• may be accessible from anywhere within a program
– private
• may be accessed only by the member functions, and friends
of this class
– protected
• acts as public for derived classes
• behaves as private for the rest of the program
14
Access Control Specifiers
• public
– Presents clients with a view of the services the class
provides (interface)
– Data and member functions are accessible
• private
– Default access mode
– Data only accessible to member functions and friends
– private members only accessible through the public
class interface using public member functions
class Time Specification
class Time
{
public :
void Set ( int hours , int minutes , int seconds ) ;
void Increment ( ) ;
void Write ( ) const ;
Time ( int initHrs, int initMins, int initSecs ) ; // constructor
Time (); // default constructor
private :
int hrs ;
int mins ;
int secs ;
};
16
16
Class Interface Diagram
Time class
Set
Private data:
Increment
hrs
Write
mins
Time secs
Time
17
Class Definition
Access Control
• The default access specifier is private
• The data members are usually private or protected
• A private member function is a helper, may only be
accessed by another member function of the same
class (exception friend function)
• The public member functions are part of the class
interface
• Each access control section is optional, repeatable,
and sections may occur in any order
18
What is an object?
OBJECT
set of methods
Operations (member functions)
Data internal state
(values of private data members)
19
Declaration of an Object
class Rectangle
main()
{ {
private: Rectangle r1;
Rectangle r2;
int width;
int length; r1.set(5, 8);
public: cout<<r1.area()<<endl;
void set(int w, int r2.set(8,10);
l); cout<<r2.area()<<endl;
int area(); }
};
20
Another Example
#include <iostream.h> // member function definitions
class circle void circle::store(double r)
{
{ radius = r;
private: }
double radius;
double circle::area(void)
{
public: return 3.14*radius*radius;
void store(double); }
double area(void);
void display(void); void circle::display(void)
{
cout << “r = “ << radius << endl;
}; }
int main(void) {
circle c; // an object of circle class
c.store(5.0);
cout << "The area of circle c is " << c.area() << endl;
c.display(); 21
}
Declaration of an Object
r1 is statically allocated
class Rectangle
{ main()
private: {
Rectangle r1;
int width;
r1.set(5, 8);
int length;
}
public:
void set(int w, int
r1
l); width = 5
length = 8
int area();
};
22
Declaration of an Object
r2 is a pointer to a Rectangle object
class Rectangle
{ main()
{
private: Rectangle r1;
int width; r1.set(5, 8); //dot notation
int length; Rectangle *r2;
r2 = &r1;
public: r2->set(8,10);
//arrow notation
void set(int w, int }
l); 5000
r1 width = 8 r2
int area(); width = 5 6000
length =
length = 8 5000
???
}; 10
23
Declaration of an Object
r3 is dynamically allocated
class Rectangle
{ main()
{
private: Rectangle *r3;
r3 = new Rectangle();
int width;
r3->set(80,100); //arrow notation
int length;
delete r3;
public: r3 = NULL;
void set(int w, int }
l);
r3
int area(); 6000 5000
5000
NULL
???
}; width = 80
length = 10024
Object Initialization
1. By Assignment
#include <iostream.h>
• Only work for public data
class circle members
{ • No control over the operations
public: on data members
double radius;
};
int main()
{
circle c1; // Declare an instance of the class circle
c1.radius = 5; // Initialize by assignment
}
25
Object Initialization
#include <iostream.h>
class circle
{ 2. By Public Member Functions
private:
double radius;
public:
void set (double r)
{radius = r;}
double get_r ()
{return radius;}
};
int main(void) {
circle c; // an object of circle class
c.set(5.0); // initialize an object with a public member function
cout << "The radius of circle c is " << c.get_r() << endl;
// access a private data member with an accessor 26
}
Declaration of an Object
r2 is a pointer to a Rectangle object
class Rectangle
{ main()
{
private: Rectangle r1;
int width; r1.set(5, 8); //dot notation
int length; Rectangle *r2;
r2 = &r1;
public: r2->set(8,10);
//arrow notation
void set(int w, int }
l);
int area(); r1 and r2 are both initialized by
public member function set
}
27
Object Initialization
3. By Constructor
class Rectangle
{
private: • Default constructor
int width;
• Copy constructor
int length;
public: • Constructor with parameters
Rectangle();
Rectangle(const Rectangle They are publicly accessible
&r);
Have the same name as the class
Rectangle(int w, int l);
There is no return type
void set(int w, int l);
Are used to initialize class data
int area();
members
}
They have different signatures
28
Object Initialization
When a class is declared with no constructors,
the compiler automatically assumes default
class Rectangle constructor and copy constructor for it.
{
private: • Default constructor
int width;
Rectangle :: Rectangle() { };
int length;
public:
• Copy constructor
void set(int w, int l);
int area(); Rectangle :: Rectangle (const
}; Rectangle & r)
{
width = r.width; length = r.length;
}; 29
Object Initialization
• Initialize with default constructor
class Rectangle
Rectangle r1;
{
Rectangle *r3 = new Rectangle();
private:
int width;
• Initialize with copy constructor
int length;
public:
Rectangle r4;
void set(int w, int l); r4.set(60,80);
int area(); Rectangle r5 = r4;
} Rectangle r6(r4);
Rectangle *r7 = new Rectangle(r4);
30
Object Initialization
class Rectangle If any constructor with any number of
parameters is declared, no default
{
constructor will exist, unless you
private: define it.
int width;
int length;
Rectangle r4; // error
public:
Rectangle(int w, int l)
{width =w; length=l;} • Initialize with constructor
void set(int w, int l);
int area(); Rectangle r5(60,80);
} Rectangle *r6 = new Rectangle(60,80);
31
Object Initialization
Write your own constructors
class Rectangle
{ Rectangle :: Rectangle()
private: {
int width; width = 20;
length = 50;
int length;
};
public:
Rectangle();
Rectangle(int w, int l); Rectangle *r7 = new Rectangle();
void set(int w, int l);
int area();
r7
} 6000
5000
??? 5000
width = 20
length = 50 32
Object Initialization
With constructors, we have more
class Account control over the data members
{
private: Account :: Account(const Account &a)
char *name; {
name = new char[strlen(a.name)+1];
double balance;
strcpy (name, a.name);
unsigned int id; balance = a.balance;
public: id = a.id;
Account(); };
Account(const Account
&a);
Account(const char Account :: Account(const char *person)
{
*person);
name = new char[strlen(person)+1];
Account
} :: Account()
strcpy (name, person);
{
name = NULL; balance = 0.0; balance = 0.0;
id = 0; id = 0;
33
}; };
So far, …
• An object can be initialized by a class
constructor
– default constructor
– copy constructor
– constructor with parameters
• Resources are allocated when an object is
initialized
• Resources should be revoked when an
object is about to end its lifetime
34
Cleanup of An Object
Destructor
class Account
{ Account :: ~Account()
private: {
delete[] name;
char *name;
}
double balance;
unsigned int id; //unique
public:
Account(); • Its name is the class name
Account(const Account preceded by a ~ (tilde)
&a); • It has no argument
• It is used to release dynamically
Account(const char allocated memory and to perform
*person); other "cleanup" activities
~Account(); • It is executed automatically when
the object goes out of scope
} 35
Putting Them Together
class Str Str :: Str() {
{ pData = new char[1];
char *pData; *pData = ‘\0’;
int nLength; nLength = 0;
public: };
//constructors
Str(); Str :: Str(char *s) {
Str(char *s); pData = new
Str(const Str &str); char[strlen(s)+1];
strcpy(pData, s);
//accessors nLength = strlen(s);
char* get_Data(); };
int get_Len();
Str :: Str(const Str &str) {
//destructor int n = str.nLength;
~Str(); pData = new char[n+1];
nLength = n;
}; strcpy(pData,str.pData);
}; 36
Putting Them Together
class Str
{
char *pData; char* Str :: get_Data()
int nLength; {
public: return pData;
};
//constructors
Str();
int Str :: get_Len()
Str(char *s); {
Str(const Str &str); return nLength;
};
//accessors
char* get_Data();
Str :: ~Str()
int get_Len();
{
//destructor delete[] pData;
};
~Str();
};
37
Putting Them Together
class Str
{
char *pData;
int nLength; int main()
public: {
//constructors int x=3;
Str(); Str *pStr1 = new Str(“Joe”);
Str(char *s); Str *pStr2 = new Str();
Str(const Str &str); }
//accessors
char* get_Data();
int get_Len();
//destructor
~Str();
};
38
When Constructors and Destructors
Are Called
• Constructors and destructors called automatically
– Order depends on scope of objects
• Global scope objects
– Constructors called before any other function
– Destructors called when main terminates (or exit function called)
– Destructors not called if program terminates with abort
• Automatic local objects
– Constructors called when objects are defined
– Destructors called when objects leave scope
• i.e., when the block in which they are defined is exited
– Destructors not called if the program ends with exit or abort
7 class CreateAndDestroy {
8 public:
9 CreateAndDestroy( int ); // constructor
10 ~CreateAndDestroy(); // destructor
11 private:
12 int data;
13 };
14
15 #endif
24
25 CreateAndDestroy::CreateAndDestroy( int
value )
26 { Constructor and Destructor
changed to print when they are
27 data = value; called.
28 cout << "Object " << data << "
constructor";
29 }
30
31 CreateAndDestroy::~CreateAndDestroy()
32 { cout << "Object " << data << "
destructor " << endl; }
42
43 void create( void ); // prototype
44
45 CreateAndDestroy first( 1 ); // global object
46
47 int main()
48 {
49 cout << " (global created before main)" << endl;
50
51 CreateAndDestroy second( 2 ); // local object
52 cout << " (local automatic in main)" << endl;
53
54 static CreateAndDestroy third( 3 ); // local object
55 cout << " (local static in main)" << endl;
56
57 create(); // call function to create objects
58
59 CreateAndDestroy fourth( 4 ); // local object
60 cout << " (local automatic in main)" << endl;
61 return 0;
62 }
OUTPUT
Object 1 constructor (global created before main)
Object 2 constructor (local automatic in main)
Object 3 constructor (local static in main)
Object 5 constructor (local automatic in create)
Object 6 constructor (local static in create)
Object 7 constructor (local automatic in create)
Object 7 destructor
Object 5 destructor Notice how the order of the constructor
Object 4 constructor (local automatic in main) and destructor call depends on the types
Object 4 destructor of variables (automatic, global and
Object 2 destructor static) they are associated with.
Object 6 destructor
Object 3 destructor
Object 1 destructor
Interacting Objects
44