Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Computational Intelligence on Automation Lab @ NCTU Learning Objectives

You should be able to review/understand:


UEE1303(1070) S’12  Procedural vs. object-oriented programming
 C++ structures versus C structures
Object-Oriented  Classes
Programming in C++ –Accessing class members
–Member functions
–Allocating objects dynamically
Lecture 03:  Constructor and destructor functions
Classes (I) – Basics, –Constructors: including copy constructors
Constructors and Destructors –Destructors
 Composition
Lecture 03 UEE1303(1070) 2

Procedural vs. Object-Oriented Procedural Programming’s Problem

 C++ supports procedural programming which  Procedural programming paradigm focuses


–solves a variety of engineering problems on program’s functionality
–decreasingly efficient for large and complex –How to represent data is not concerned
program development – func_1 + func_2 + … + func_n
 C++ also supports object-oriented  For large and complex programs, procedural
programming which programming faces the difficulties of
–is more natural as the logic applied to real- –maintaining and modifying the program
life problems –debugging and following its logic
–programmers have difficulty in adopting –too many disorganized, overloaded details
such paradigm –creation of inadvertent logic errors
Lecture 03 UEE1303(1070) 3 Lecture 03 UEE1303(1070) 4
Sample Problem from Structure OOP Paradigm

struct SScore {  OOP overcomes the above problems by


char name[20]; –using a collection of objects that
int subj[3]; communicate with each other through their
};
double computeAverage(SScore one) { interface functions
return (one.subj[0]+one.subj[1]+ –focusing on both data and operations
one.subj[2])/3;  Three important concepts in OOP:
} –Encapsulation binds data and functions into
one capsule (object)
 Potential problems: –Inheritance enables new codes to be
–the number of subjects is changed to 4 derived from existing codes
–computeAverage() may change the user –Polymorphism uses the same functions on
name unintentionally different types of objects
Lecture 03 UEE1303(1070) 5 Lecture 03 UEE1303(1070) 6

Concept of Class Class Declaration (1/2)

 Class is a foundation of OOP  Defined similar to structures


–expands structure by binding together data class class_name class head
and functions {
public:
–variables in class types are objects //public variables and functions
 A object has its own unique identity, state and protected: member access
behaviors //protected modifier class body
variables and functions
private:
–states  data fields //private variables and functions
–behaviors  a set of functions };
 Class is the abstraction of objects  A object –Class name must be a legal identifier,
is an instance of class typically starting with C or T
–Class is abstract  takes no memory –Class body includes many data members
–Object is concrete  takes memory space (variables) and member functions (methods)
Lecture 03 UEE1303(1070) 7 Lecture 03 UEE1303(1070) 8
Class Declaration (2/2) Two Ways to Define Classes

 Member access modifiers can appear in an  First declare class, then define objects  the
arbitrary order or multiple times most common
– public: members can be accessed by class someclass
members of its class or those of any other {
class or any non-member function ...//implement data and functions
};
– private: members serve only as utility someclass obj1, obj2, ..., objn;
functions for others of the same class
– protected: used only with inheritance;  Declare class and define objects right away
members can be accessed by other class someclass
members of its class or the derived class {
...//implement data and functions
 The default modifier for class is private  } obj1, obj2, ..., objn;
the default for struct is public
Lecture 03 UEE1303(1070) 9 Lecture 03 UEE1303(1070) 10

Memory Allocation for Objects Access Members in Objects

 Need to allocate memory for data members  Members in objects can be accessed by
and member functions of every object –(1) object name and dot (.) operator
–Objects of the same class use the same CScore stu1;
functions  memory waste cout << stu1.name;
stu1.computeAverage();
data data data
member member member –(2) a pointer to the object and arrow (->)
… operator
member member member
functions functions functions CScore * pStu = &stu1;
obj1 obj2 objn pStu->computeAverage();
data data data –(3) a reference to the object and dot (.)

In C++
member member member operator
member functions CScore & rStu = stu1;
rStu.computeAverage();
Lecture 03 UEE1303(1070) 11 Lecture 03 UEE1303(1070) 12
Scopes for Class (1/2) Scopes for Class (2/2)

 The scope of a class is enclosed by { and }  Class prototype scope: declares the class
–can define variables and functions name before being used
–Variables in class cannot be modified by class 〈name〉;
auto, register and extern (except static)  Example
–Functions in class cannot be modified by class COne; //class prototype
extern but inline class COne; //repetition is OK!
class CTwo {
 Scope for class name typically starts from the ...
declaration line to the file end COne a; //use declared class
};
–If put in the header file, its scope starts class COne { //the actual body
after the preprocessor directives to the end ...
of the program };
Lecture 03 UEE1303(1070) 13 Lecture 03 UEE1303(1070) 14

Functions in Class Member Functions (1/3)

 Member functions are one kind of functions  Example for member functions in class body
–Class without member functions = struct class CScore
{
–Belongs to class  need to consider private:
accessibility (access modifier) char name[20];
int subj[3];
 Member functions can be defined into public:
–Functions defined in the class body: double computeAverage() {
return (subj[0]+subj[1]+subj[2])/3.0;
default as inline functions that are allowed }
to be included in the header files void setName(char * inName) {
strncpy(name, inName, 20);
–Function declared in the class body: the }
typical case; function definitions are ...
written outside the class };
Lecture 03 UEE1303(1070) 15 Lecture 03 UEE1303(1070) 16
Member Functions (2/3) Member Functions (3/3)

 Member functions outside class body  Separating declaration from implementation is


class CScore
due to (1) information hiding and (2)
{ intellectual property protection
private:  You are free to change the implementation
unlike normal functions, parameters in
char name[20]; but the client program needs not to change as
int subj[3];
public: member functions need to be specified long as the declaration is the same
double computeAverage(); double CScore::computeAverage()
void setName(char * inName); {
... return ((1*subj[0]+2*subj[1]+
}; default is not inline  need to specify 3*subj[2])/3.0); //weighted version
inline double CScore::computeAverage() }
{  As a software vendor, only provide the
return (subj[0]+subj[1]+subj[2])/3.0;
} customer with the header file and class object
field qualifier (::) code without revealing the source codes
Lecture 03  tell the function
UEE1303(1070) belongs to what class
17 Lecture 03 UEE1303(1070) 18

Preventing Multiple Declarations Accessor and Mutator Functions

 A common compiling error is to include the same  The private data field cannot be accessed
header files multiple times in a program outside the class.
–Ex: head1.h includes circle.h and –to make them readable, provide a get
testHead.cpp includes head1.h and circle.h
function to return the field’s value 
 Preprocessor directives solve this issue accessor functions
#ifndef CIRCLE_H
#define CIRCLE_H returnType getPropertyName()
–to make them updatable, provide a set
//original class declaration in circle.h
class CCircle { function to set a new value in the field 
... mutator functions
};
void setPropertyName(datatype value)
#endif
Lecture 03 UEE1303(1070) 19 Lecture 03 UEE1303(1070) 20
Example of Accessor & Mutator Constructors and Destructors

class CScore  Many errors starts from incorrect initialization


{ or clearance of variables in C++
private:
char name[20]; –two special member functions: constructors
int subj[3]; and destructors
public:
double computeAverage() {  Constructors aims at assigning values for
return (subj[0]+subj[1]+subj[2])/3.0; data members when creating objects
}
void setName(char * inName) { //mutator  object initialization
strncpy(name, inName, 20);
}  Destructors aims at freeing memory space for
char *getName() { //accessor data members when destroying objects
return name;
}  object cleaning
};
Lecture 03 UEE1303(1070) 21 Lecture 03 UEE1303(1070) 22

Constructor Functions (1/2) Constructor Functions (2/2)

 Typically, can only access private data member  A constructor function has the name as the
by calling member functions manually class itself with or without parameters
–Constructor functions automatically runs –can be overloaded  multiple functions
when creating an object with the same names
class CScore –can have default parameter values
{  May call different versions of constructors
private:
char name[20]; CScore one;
int subj[3]; one.CScore(“Tom”, {66, 70, 80});
}; one.CScore(“Tom”);
one.CScore({66, 70, 80});
CScore one = {“Tom”, {66, 70, 80}}; one.CScore();
CScore one; –imply overloaded functions
one.setValue(“Tom”, {66, 70, 80});
Lecture 03 UEE1303(1070) 23 Lecture 03 UEE1303(1070) 24
Example of Constructor Versions More about Constructors

CScore::CScore(char* str, double* dary) {  Constructors are like other normal member
strncpy(name, str, 20);
subj[0] = dary[0]; functions but
subj[1] = dary[1]; –have the same name as the class
subj[2] = dary[2]; –cannot specify the return type, even void
}
–must be public (or can be protected for
CScore::CScore(char* str) {
strncpy(name, str, 20); derived classes)
} –avoid ambiguity from the default
CScore::CScore(double* dary) { parameters in overloaded functions
subj[0] = dary[0]; CScore::CScore(char* str,
subj[1] = dary[1]; double* dary={0,0,0}) {...}
subj[2] = dary[2];
} CScore::CScore(char* str) {...}
CScore::CScore() {;} one.CScore(“Tom”); //call which version?
Lecture 03 UEE1303(1070) 25 Lecture 03 UEE1303(1070) 26

Default Constructor Copy Constructor

 If no constructor is defined, the compiler  What if using a existing object to initialize the
implicitly generate a default constructor new object? Ex:
without any parameter CScore one(old);//old is declared before
–Ex: CScore::CScore() {;} –need a different type of constructors
 If any constructor is defined, need to specify a  Copy constructor
default constructor explicitly 〈CNAME〉::〈CNAME〉(const 〈CNAME〉 & 〈var〉) {
CScore two;//error if no default const. //copy constructor: function body
};
 Initialized values in default constructor
– 〈CNAME〉 is the class name
depend on the datatype of the object – 〈var〉 is the name for formal parameter of
–initialized values are random, ex: copied object
CScore one;
–If no copy constructor is specified, the
–initialized values are 0 or empty, ex: compiler automatically generate one
static CScore one;
Lecture 03 UEE1303(1070) 27 Lecture 03 UEE1303(1070) 28
Example of Copy Constructors (1/2) Example of Copy Constructors (2/2)

class CStr
{ CStr::CStr(char * word) //A
private: {
char * line;//default access is private line = new char [strlen(word)+1];
public: strcpy(line, word);
CStr(char* word); //A }
CStr(const CStr & old); //B
void ShowCStr(); CStr::CStr(const CStr & old) //B
}; {
line = new char [strlen(old.line)+1];
int main() { strcpy(line, old.line);
CStr one(“prog3-1”); //call A }
CStr two(one); //call B; CStr two = one;
two.ShowCStr(); void CStr::ShowCStr(){
return 0; cout << line << endl;
} }
Lecture 03 UEE1303(1070) 29 Lecture 03 UEE1303(1070) 30

Destructor Functions Example of Constructor/Destructor (1/2)

 Destructor function is the complement of a class CStr


{
constructor function private:
–need to clean up the object char * line;
–unlike constructors, only one destructor public:
CStr() { line = NULL; } //A
–the compiler automatically generates one if CStr(char* cline) { line = cline; } //B
no destructor is declared ~CStr() {}
 A destructor has the following properties: };
–its name = tilde (~) + class name int main() {
–should be public char* p = “prog3-2”;
CStr one(p); //call B
–cannot have a return type
–cannot have any parameter one.~CStr(); //call destructor
–automatically called when the object goes return 0;
}
out of scope
Lecture 03 UEE1303(1070) 31 Lecture 03 UEE1303(1070) 32
Example of Constructor/Destructor (2/2) Understanding Composition

 Modified constructor and destructor  Composition  uses an object of one class


class CStr within the object of another class
{
private: –forms a “has-a” relationship
char * line; –top-level class are called composed classes
public: –contained objects are called member objects
CStr() { line = NULL; } //A
CStr(char* cline) {  Example: A CScore class has a CStr object
line = new char [strlen(cline)+1];
strcpy(line, cline); class CScore //composed class
} //B {
~CStr() { private:
if (line) delete [] line; CStr name; //member object
line = NULL; cout << “done” << endl; int subj[3];
} public: ...
}; };
Lecture 03 UEE1303(1070) 33 Lecture 03 UEE1303(1070) 34

Example for Composed Class (1/3) Example for Composed Class (2/3)
class CPoint {  Can CRect be declared as follows?
int x, y; class CRect {
public:
CPoint() { x=0; y=0; } CPoint p1(0,0); //top-left point
CPoint(int a, int b) { x=a; y=b; } CPoint p2(0,0); //bottom-right point
void set(int a, int b) { x=a; y=b; } ...
void move(int a, int b) { x+=a; y+=b; } };
};
class CRect {  Can a CRect constructor be defined as follows?
CPoint p1, p2;//give two points
public: CRect::CRect(int a, int b, int c, int d) {
CRect() { p1.set(0,0); p2.set(0,0); } p1(a,b); //top-left point
CRect(int a, int b, int c, int d) { p2(c,d); //bottom-right point
p1.set(a,b); p2.set(c,d); } ...
CRect(const CPoint &q1, const CPoint &q2){
p1 = q1; p2 = q2; } }
};
 Both answers are NO!
Lecture 03 UEE1303(1070) 35 Lecture 03 UEE1303(1070) 36
Example for Composed Class (3/3) Summary (1/2)

 The first solution for legal initialization is  Review OO concept and programming:
CRect(int a, int b, int c, int d) {
p1.set(a,b); p2.set(c,d); } –Procedural programming’s problem
CRect(const CPoint &q1, const CPoint &q2){ –Three concepts of OOP paradigm
p1 = q1; p2 = q2; }
 The second solution creates a new copy –What is the relationship between class and
constructor in class CPoint object?
//class CPoint  Class declaration
CPoint(int a, int b) { x=a; y=b; }
CPoint(const CPoint &old) { –Data members and function members
x = old.x; y = old.y; } –Three access modifiers
//class CRect
CRect(int a, int b, int c, int d) : –Two ways to define classes and declare
p1(a,b), p2(c,d) {} objects
CRect(const CPoint &q1, const CPoint &q2):
p1(q1), p2(q2) {} –Memory allocation for objects
Lecture 03 UEE1303(1070) 37 Lecture 03 UEE1303(1070) 38

Summary (2/2)

 Using objects
–Three ways to access members in objects
–Scopes for class
 Member functions
–Separate declaration from implementation
–Preventing multiple declarations
–Accessor and mutator functions
–Constructors: default and copy ones
–Destructors
 Composition
–Composed classes and object members
–Legal initialization
Lecture 03 UEE1303(1070) 39

You might also like