0% found this document useful (0 votes)
34 views12 pages

3 - 1 - Classes (Part 1)

Uploaded by

thabotwn2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views12 pages

3 - 1 - Classes (Part 1)

Uploaded by

thabotwn2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

CLASSES

C++ Classes

Class Introduction
• Type: concrete instance of a concept, said to model the concept.
• Concept: places a set of requirements on a type
• Class: user defined type, separate implementation from properties
• Concrete type: simple, not derived
• typical concrete Class structure:
class Date {
int d, m, y;
public: // default is private
-- constructors --
-- access methods (const)--
-- manipulator methods --
-- implicit or explicit copy operators --
-- exception class –
}
• Member functions may be defined in separate context (for example the .cpp file
with the class declaration in a .h file).
• If a member function is defined in the declaration then it is inlined.
2

1
C++ Class
• This class example shows how we can
encapsulate (gather) a circle information into
one package (unit or class)
No need for others classes to access
class Circle and retrieve its value directly. The
{ class methods are responsible for
that only.
private:
double radius;
public:
void setRadius(double r); They are accessible from outside
double getDiameter(); the class, and they can access the
double getArea(); member (radius)
double getCircumference();
};

What to put in header files


Yes No
• Named namespaces • Ordinary function definitions
• Type definitions • Data definitions
• Template declarations • Aggregate definitions
• Template definitions • Unnamed namespaces
• Function declarations • Exported template definitions
• Inline function definitions
• Data declarations
• Constant definitions
• Enumerations
• Name declarations
• Include directives
• Macro definitions
• Conditional compilations directives
• Comments

2
Access control
• Access control: use public or private keywords
(default is private). A struct is == class with all
members public. Non-member functions can not
access private members.

class Date {
public:
Date(int m, int d, int y);

private:
int m_, d_, y_;
}

static class members


• A static member is part of the class but not of any particular object (instance of
the class).
• Static object referenced using class name, Date::default_date
• Must define static members someplace, usually outside of class.
– non-const data members must be initialized outside of class
class Date { Date Date::default_date(01,01,2004);
int d_, m_, y_;
static Date default_date; void Date::set_default(int m, int d, int y)
public: {
Date(…); Date::default_date = Date(m, d, y);
… }
static void
set_default(int,int,int);
};
Date::Date(int m, int d, int y)
{
d_ = d ? d_ : default_date.d_;
m_ = m ? m_ : default_date.m_;
y_ = y ? y_ : default_data.y_;
}
6

3
Creating an object of a Class
• Declaring a variable of a class type creates an object.
You can have many variables of the same type (class).
– Instantiation
• Once an object of a certain class is instantiated, a new
memory location is created for it to store its data
members and code
• You can instantiate many objects from a class type.
– E.g) Circle c; Circle *c;

Special Member Functions


• Constructor:
– Public function member
– called when a new object is created (instantiated).
– Initialize data members.
– Same name as class
– No return type
– Several constructors
• Function overloading

4
Special Member Functions

class Circle
Constructor with no
{
argument
private:
double radius;
public: Constructor with one
Circle(); argument
Circle(int r);
void setRadius(double r);
double getDiameter();
double getArea();
double getCircumference();
};

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)
{
Defined outside class
radius = r;
}
double Circle::getArea()
{
return radius * radius * (22.0/7);
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}

5
Default constructor
• Takes no arguments

• Compiler will generate a default constructor unless


– (1) the class defines any constructors
– (2) class contains a const or reference type
– (3) class contains an object without a default constructor

• Built-in types are initialized using the same rules as


already described: local scope not initialized, global
scope initialized to zero.
– Preserves compatibility with C

11

Destructors
• Destructors
– Special member function
– Same name as class
• Preceded with tilde (~)
– No arguments
– No return value
– Cannot be overloaded
– Before system reclaims object’s memory
• Reuse memory for new objects
• Mainly used to de-allocate dynamic memory locations

6
Destructors
• While constructors create new instances of a class, a destructor is
used to “clean up” after an object is no longer needed.
– ~X : destructor for object X
• Implicitly called when object is destroyed
– is not called when pointers and reference to objects go out of
scope.
– However if delete is called on a pointer then the
corresponding destructor is called.
• Member objects have their destructors called in the reverse order
of their declarations.
• If a destructor is not defined the compiler will synthesize one.
• Constructor allocates some resources (memory) then a destructor
is defined to release this memory when object is deleted.
13

Constructors/Destructors
• Destructor example
• Constructor allocates memory for string
• Destructor must deallocate memory
Student::Student (char *n)
class Student { {
char *name_; if (n == NULL) {
… name = new char[DefBufSz];
public: *name = ‘\0’;
Student(char *n=null); } else {
~Student(); name = new char[strlen(n)+1];
… strcpy(name, n);
} }
}
Student::~Student()
{
cout << “Calling destructor\n”;
if (name)
delete [] name;
} 14

7
new
• The operator new allocates memory from the free
store
• the operator delete frees memory allocated by new
• you must free all memory allocated (no garbage
collection)
• it is an error to call delete two or more times on the
same memory location
• you can overload (redefine) these operators, the
placement syntax

void *operator new(size_t, void *p) {return p;}


15

Accessing Class Members


• Operators to access class members
– Identical to those for structs
– Dot member selection operator (.)
• Object
• Reference to object
– Arrow member selection operator (->)
• Pointers

8
class Circle
{
private:
double radius;
public: The first
Circle() { radius = 0.0;} The second
constructor is
Circle(int r); constructor is
called
void setRadius(double r){radius = r;} called
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:”
radius = r; <<c1.getArea()<<“\n”;
}
double Circle::getArea() //c1.raduis = 5;//syntax error
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:”
return 2 * radius * (22.0/7); <<c2.getDiameter()<<“\n”;
} }

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 area of cp2:”
return radius * radius * (22.0/7); <<cp2->getArea();
}
}
double Circle:: getCircumference()
{
return 2 * radius * (22.0/7);
}

9
Another class Example
• This class shows how to handle time parts.
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;}
Destructor 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 Time::Time(int h,int m,int s)


should be allocated to }
pointers first hour = new int;
minute = new int;
second = new int;
*hour = h;
*minute = m;
*second = s;
{

void Time::setTime(int h,int m,int s)


}
*hour = h;
*minute = m;
*second = s;
{

10
void Time::printTime()
}
cout<<"The time is : ("<<*hour<<":"<<*minute<<":"<<*second<<")"
>>endl;
{
Destructor: used here to de-allocate
Time::~Time() memory locations
}
delete hour; delete minute;delete second;
{

void main()
Output:
}
Time *t; The time is : (3:55:54)
t= new Time(3,55,54); The time is : (7:17:43)
t->printTime(); Press any key to continue

t->setHour(7);
t->setMinute(17);
t->setSecond(43);

t->printTime(); When executed, the destructor


is called
delete t;
{

Tags and struct


• When using struct command in C++ (and for other
tagged types), can create type using tag format and
not use tag in variable declaration:
struct MyType {
int A;
float B;
};
MyType V;

11
enum in C++
• Enumerated types not directly represented as
integers in C++
– certain operations that are legal in C do not work in C++
• Example:
void main() {
enum Color { red, blue, green };
Color c = red;
c = blue;
c = 1; // Error in C++
++c; // Error in C++

Virtual functions

24

12

You might also like