0% found this document useful (0 votes)
10 views

05-Overview of C++ (Classes)

Uploaded by

gurujeeltd989
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

05-Overview of C++ (Classes)

Uploaded by

gurujeeltd989
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Data Structures

CT077-3-2- DSTR and Version VC1

Classes and Objects


Topic Structure

• Classes and object


• Struct and classes
• Constructors
• Dynamically allocated object
• Destructors

CT077-3-2-DSTR Data Structures 2


Learning Objectives

By the end of this lesson, you would:


• Learn about classes and objects in C++
• Explore how to define the classes and member
functions, and declare objects
• Examine how constructors of a class work
• Learn how to create an array of objects
• Learn how to use pointers to class objects
• Examine how destructors work

CT077-3-2-DSTR Data Structures 3


Key Terms

• Class
• Object
• Constructor
• Destructor

CT077-3-2-DSTR Data Structures 4


Classes and Objects

• Classes are categories of things (objects) in the


world
– An object (thing) belongs to a class (category)
• Each class has properties (attributes) that describe it
– Objects have specific values for each of the attributes of
the class they belong to
• Class examples
– Car: maker, model, engine, etc.
– Facebook user: name, id, birthdate, friends, etc.
• Car object example
• My car: maker:toyota, model:vitz, engine:1.6, etc.
CT077-3-2-DSTR Data Structures 5
Structs and Classes

• Both are used to model objects with multiple


attributes (characteristics)
– represented as data members
– also called fields

• Thus, both are used to process non-


homogeneous (heterogeneous) data elements

CT077-3-2-DSTR Data Structures 6


Classes

• C++ classes model objects which have:


– Attributes represented as data members
– Operations represented as functions (or
methods)

• Leads to object oriented programming


– Objects are self contained
– Call objects methods instead of passing the
object as a parameter to an external function

CT077-3-2-DSTR Data Structures 7


Class Declaration

class ClassName
{
public:
Declarations of public members
private:
Declarations of private members
};

class Rectangle {
private:
int width, height;
public:
void setSize (int, int) { … }
int area (void) { … }
};
CT077-3-2-DSTR Data Structures 8
Rectangle Class Example
Declares a class called
// classes example Rectangle
#include <iostream>
using namespace std;
Everything inside this opening
class Rectangle { brace and the corresponding
int width, height; closing brace is part of the class
public:
void setSize (int,int); Two data members (width and
int area () { height) with private access
return (width*height); (because private is the default
} access level)
};

area is a public function setSize is a public function member


member of Rectangle. of Rectangle.
Notice that we can include Notice that we can include only the
the definition of the function signature of the function inside the
inside the class also class (implementation can come later)
CT077-3-2-DSTR Data Structures 10
Rectangle Class Example
// classes example void Rectangle::setSize (int a, int b) {
#include <iostream> width = a;
using namespace std; height = b;
}
class Rectangle {
int width, height;
public:
void setSize (int,int); Function definition for setSize can be done
int area () { outside Rectangle class definition itself.
return (width*height); We must use the operator of scope (::) to
} specify that we are defining a function that is a
}; member of the class Rectangle.
This is not mandatory, but can help to keep
class declaration code concise and separate,
and implement the methods in another file

CT077-3-2-DSTR Data Structures 11


Rectangle Class Example

void main () { Creates an object (variable) of


Rectangle rect; type Rectangle. Like any local
variable, this object is located in
rect.setSize(3,4); Stack memory.
In Java, similar code will rather
cout << "area: " << rect.area(); declare an empty reference only,
and doesn’t create the object itself
}

To access rect’s public members we use


the object's name (rect) followed by a
dot (.) and then the name of the member

CT077-3-2-DSTR Data Structures 12


Rectangle Class Example

void main () {
Rectangle rect;
rect.setSize(3,4);
cout << "area: " << rect.area();
We can also create the object in
Rectangle * r = new Rectangle; heap memory, and operating on it
r->setSize(5,6); using a pointer.
cout << "area: " << r->area(); Must delete the object once done
delete r;

return 0;
}

CT077-3-2-DSTR Data Structures 13


Objects Assignment

object1 = object2;
• This will copy/clone values of each data member
of object2 to corresponding members of object1
void main () {
Rectangle rect1; rect1.setSize(3,4);
Rectangle rect2; rect2.setSize(5,6);
cout << "area1: " << rect1.area();
cout << "area2: " << rect2.area();
rect1 = rect2;
cout << "area1: " << rect1.area();
cout << "area2: " << rect2.area();
rect1.setSize (7,8);
cout << "area1: " << rect1.area();
cout << "area2: " << rect2.area();
}
CT077-3-2-DSTR Data Structures 14
Objects Assignment - Java
What’s the public class Rectangle {
int width, height;
output if we do int area() {
return (width*height); First rectangle
similar thing in } gets de-allocated
Java? will make both of
Assignment
void setSize (int a, int b) {
width = a; height = b;
from memory by
garbage collector
rect1 and rect2 as references }
to the same object, rather public static void main (String [ ] args){
than copying corresponding Rectangle rect1 = new Rectangle();
fields values of rect2 to rect1 Rectangle rect2 = new Rectangle();
rect1.setSize(3,4); rect2.setSize(5,6);
rect1 = rect2;
System.out.println("area1: " +
rect1.area());
Actually changing dimensions System.out.println("area2: " +
of the same object being rect2.area());
referenced by rect1 and rect2 rect1.setSize(7,8);
System.out.println("area1: " +
rect1.area());
System.out.println("area2: " +
CT077-3-2-DSTR
rect2.area());
Data Structures 15
Static Members of a Class

• Use the keyword static to declare a function


or variable of a class as static

• A public static function or member of a


class can be accessed using the class name
and the scope resolution operator ::

• static member variables of a class exist even


if no object of that class type exists

CT077-3-2-DSTR Data Structures 16


Static Members Example
This is a declaration of static member.
class A { Unlike Java, you cannot initialize class
public: static int sValue; members right away after their
}; declaration (ex: int sValue = 1;)
int A::sValue = 1;
Non-static data members are initialized
void main () { in constructors, and static members in
A a1, a2; CPP files after class declaration
a1.sValue++;

cout << "a1.sValue: " << a1.sValue << endl;

a2.sValue++;
A::sValue++;

cout << "a2.sValue: " << a2.sValue << endl;


cout << "a1.sValue: " << a1.sValue << endl;
}
CT077-3-2-DSTR Data Structures 17
Constructors

• A constructor is a member function that is


automatically called when an object is created
• It is used to properly initialize\configure an
object upon its creation
• It has the same name as the class
• If a class does not declare any constructor(s),
C++ provides a default constructor implicitly
• This allows us to declare: Rectangle rect;
• Implicit default constructor contains no actual code

CT077-3-2-DSTR Data Structures 18


Constructor Example

// classes example Rectangle::Rectangle (int a, int b) {


#include <iostream> width = a;
using namespace std; height = b;
} A constructor that takes
class Rectangle {
values for the width and
int width, height;
height member variables
public: int main ()
Rectangle (int,int);
{
int area () {
Rectangle rect (3,4);
return (width*height); cout << "area: " << rect.area();
} return 0;
}; }
Pass the parameters to the constructor.
Be aware that the default (with-no-parameters)
constructor is not implicitly provided once any
constructor is defined by the programmer
CT077-3-2-DSTR Data Structures 19
Constructors Overloading

• You can overload a constructor (have more than one


with different number and/or type of parameters)

Rectangle::Rectangle () { //defining our own default


constructor
width = 5;
height = 5;
}
Rectangle::Rectangle (int a, int b) {
width = a;
height = b;
}
Rectangle::Rectangle (int a) {
width = a;
height = a;
}
CT077-3-2-DSTR Data Structures 20
Array of Objects

• As with any other data type in C++, you can define


arrays of class objects
const int ARRAY_SIZE = 40;
Rectangle rects[ARRAY_SIZE];

• Array objects are created using default constructor


(so must have one if implicit is not provided)

• Objects in an array are accessed with subscripts,


just like any other data type in an array
rects[2].setSize(5, 4);
CT077-3-2-DSTR Data Structures 21
Pointers to Class Objects

• It is possible to declare pointers to class objects


• Same syntax is used for pointers to structs
Rectangle rect(10,5);
Rectangle *rectPtr = &rect;
rectPtr rect
width 10
height 5

• Accessing the members of the class


(*rectPtr).area();
rectPtr-> area();
CT077-3-2-DSTR Data Structures 22
Dynamically Allocated objects
• When the Rectangle object is created by new
operator, the proper constructor is automatically
executed.
Rectangle *rectPtr = new Rectangle;
Rectangle *rectPtr2 = new Rectangle(2,4);

• Accessing the member of the class through a


pointer.
(*rectPtr).setSize(4, 4);
rectPtr->setSize(4, 4);

CT077-3-2-DSTR Data Structures 23


“this” Pointer

• Inside any method definition for a class, C++


provides a special pointer (called: this) to reference
the object whose method is being called
Rectangle::setSize (int width, int height) {
this -> width = width; // (*this).width
this -> height = height;
}

• Similar to Java, but using a pointer rather than a


“reference”
CT077-3-2-DSTR Data Structures 24
Destructors

• Destructors are functions used to properly kill /


delete an object. Usually used to:
– free dynamic memory
– perform program housekeeping
– keep track of class related data
• The name of a destructor is the character '~'
followed by class name
– For example: ~Rectangle(){ }
• A class can have only one destructor
– The destructor has no parameters, and no type
– Implicitly provided if a class does not define one
CT077-3-2-DSTR Data Structures 25
Destructors

• The destructor is automatically executed when


the class object goes out of scope, or when a
dynamic heap object gets deleted
Rectangle *rectPtr = NULL;
if ( someCondition) {
Rectangle rect;
*rectPtr = new Rectangle;
}
if (rectPtr)
delete rectPtr ;
CT077-3-2-DSTR Data Structures 26
Passing Objects to Functions

• Objects, similar to simple types, can be passed as


parameters by value, by reference, or using
pointers, and can be returned by functions
– If an object is passed by value, contents of data members
of the actual parameter are copied into the corresponding
data members of the formal parameter
– Passing by value might require a large amount of memory
space and a considerable amount of time to copy the
value of the actual parameter into the formal parameter
– If a variable is passed by reference, the formal parameter
receives only the address of the actual parameter

CT077-3-2-DSTR Data Structures 27


The Copy Constructor

• A special constructor is implicitly called by C++ in


few scenarios:
– An object is declared and initialized from another object
Rectangle r1; Rectangle r2(r1); Rectangle r3 = r1;
– An object is passed to a function as parameter by value
void func (Rectangle rec) { … }
Rctangle r1; func(r1);
– An object is returned by value from a function
Rectangle func () {Rectangle rec; … return rec; }
Rctangle& r1 = func();

• General syntax for the copy constructor is


ClassName (ClassName & objectToBeCopied) { … }

CT077-3-2-DSTR Data Structures 28


When to Define a Copy
Constructor
• A default copy constructor is provided by C++, which
performs a “shallow copy” of object’s data members
– Will be sufficient, unless the object has pointers to dynamically
allocated memory, or some other management of resources

• If the object contains memory dynamically allocated which


needs to be deleted in the destructor, most probably we need
to write the copy constructor to perform “deep copy”
– Means that a simple copy of each data member is not enough to
create a correct copy of the object

CT077-3-2-DSTR Data Structures 29


CT077-3-2-DSTR Data Structures 30
Copy Constructor Example
class DArray { void main () {
public: DArray first(20);
int size; first.data[0] = 25;
int* data;
if (true) {
DArray(int s) { DArray temp = first; //shallow copy
size = s; cout << first.data[0] << endl;
data = new int [size]; cout << temp.data[0] << endl;
} }

~ DArray() { first.data[0] = 10;


delete[] data; }
}
temp‘s data array has been deleted from the heap
}; when temp was destructed. However, temp and
first share the same pointer to the data array.
Accessing the array using first’s data pointer is wrong, and
may cause memory error. When first is to be destructed,
another attempt to delete the array may cause an error.
CT077-3-2-DSTR Data Structures 31
Copy Constructor Example-Solution
class DArray { void main () {
public: DArray first(20);
int size; first.data[0] = 25;
int* data;
DArray(int s) { if (true) {
size = s; DArray temp = first; //deep copy
data = new int [size]; cout << first.data[0] << endl;
} cout << temp.data[0] << endl;
~ DArray() { }
delete[] data;
} first.data[0] = 10;
DArray(DArray& other){ }
size = other.size;
data = new int [size];
for(int i= 0; i<size; i++) temp has a separate complete copy of
data[i] = other.data[i]; first’s array, and therefore no errors will
} happen when temp’s array is deleted.
};
CT077-3-2-DSTR Data Structures 32
Exercise 1. Learn to use and
build a class in C++

Question: Suppose you want to keep track of your books in a library. You might
want to track the following attributes about each book:
 Title
 Author
 Subject
 Book ID
Here you can define a structure for grouping all the data in once.

To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member for your program

CT077-3-2-DSTR Data Structures 33


Exercise 2. Learn to use and
build a struct in C++

Question: Suppose you want to keep track of your books in a library. You might
want to track the following attributes about each book:
 Title
 Author
 Subject
 Book ID
Here you can define a class for grouping all the data in once.

To define a class, you must use the class statement. The class statement defines a new data type, with
more than one member for your program

CT077-3-2-DSTR Data Structures 34


Struct Class

CT077-3-2-DSTR Data Structures 35


Exercise 3.
Question: Suppose you want to keep track of your flowers in your garden. You
might want to track the following attributes about each flower:
 Flower Name
 Flower ID
 Flower Location
 Flower Pick Date

Here you can define a structure & a class for grouping all the data in once.

To define a class, you must use the class & struct statement. The class & struct statement defines a
new data type, with more than one member for your program. Use the pointer to create a dynamic
structure.

CT077-3-2-DSTR Data Structures 36


#include <iostream>
#include <string>
using namespace std;

class flower
{
public :
int flowerid;
string flowername;
string flowervenue;

};

int main()
{
flower * flower1 = new flower ();
flower1->flowerid = 1;
flower1->flowername = "SunFlower";
flower1->flowervenue = "Poland";

cout << "Flower ID: " << flower1->flowerid << endl;


cout << "Flower Name: " << flower1->flowername << endl;
cout << "Flower Birth Venue: " << flower1->flowervenue << endl;

return 0;

CT077-3-2-DSTR Data Structures 37


#include <iostream>
#include <string>
using namespace std;

struct flower
{
int flowerid;
string flowername;
string flowervenue;
};

int main()
{
flower * flower1 = new flower ();
flower1->flowerid = 1;
flower1->flowername = "SunFlower";
flower1->flowervenue = "Poland";

cout << "Flower ID: " << flower1->flowerid << endl;


cout << "Flower Name: " << flower1->flowername << endl;
cout << "Flower Birth Venue: " << flower1->flowervenue << endl;

return 0;

CT077-3-2-DSTR Data Structures 38


Homework
• Write a C++ program which deals with mathematical
polynomials:
class Polynomial {
private:
int degree; double* coefficients;
public:
Polynomial(int degree) { … } //creates a polynomial object of certain degree

Polynomial(int degree, double coefs[]) { … } //initialize coefficients using array

Polynomial(Polynomial& other) { …} //copy constructor

~ Polynomial() { … } //destructor

Polynomial* add(Polynomial& other) { … } //returns sum of two polynomials

void print() { … } //prints a suitable representation of the polynomial


};
CT077-3-2-DSTR Data Structures 39
Homework
• A sample program which uses Polynomial class:
void main () {

double coefs1 [] = {1.5, -2, 0, 2, 6};


Polynomial p1(4, coefs1);
p1.print();

double coefs2 [] = {2.3, 5, -3, 0};


Polynomial p2(3, coefs2);
p2.print();

Polynomial * resultPtr = p1.add(p2);


resultPtr ->print();
delete resultPtr;
}

CT077-3-2-DSTR Data Structures 40


Summary of Main Teaching

• Classes and object


• Struct and classes
• Constructors
• Dynamically allocated object
• Destructors

CT077-3-2-DSTR Data Structures 41


CT077-3-2-DSTR Data Structures 42
What we will cover next

• Linked-list
– Introduction
– Properties

CT077-3-2-DSTR Data Structures 43

You might also like