object oriented programming in c++ · compiling multiple .cpp les wenqiang chen object oriented...

33
Structure Classes & Objects Inheritance Polymorphism Additional contents Object Oriented Programming in c++ Wenqiang Chen Department of Computing and Software McMaster University Tutorial 11 Wenqiang Chen Object Oriented Programming in c++

Upload: others

Post on 16-Jun-2020

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Object Oriented Programming in c++

Wenqiang Chen

Department of Computing and SoftwareMcMaster University

Tutorial 11

Wenqiang Chen Object Oriented Programming in c++

Page 2: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Outline I

1 Structure

2 Classes & ObjectsMember FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Function OverloadingOperator Overloading

3 InheritanceInheritanceRedefining functionsconstructor and destructor in derived class

Wenqiang Chen Object Oriented Programming in c++

Page 3: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Outline II

4 PolymorphismPolymorphismVirtual FunctionVirtual DestructorExample

5 Additional contentsHeader filesCompiling multiple .cpp files

Wenqiang Chen Object Oriented Programming in c++

Page 4: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Structure

Definition: A group of data elements grouped together under onename.

struct type_name {member_type1 member_name1;member_type2 member_name2;member_type3 member_name3;..

};

or

struct type_name {member_type1 member_name1;member_type2 member_name2;member_type3 member_name3;..

} object_names;

Wenqiang Chen Object Oriented Programming in c++

Page 5: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Structure example

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

struct contact_info {string name;int age;string address;

} person1, person2;

void printContact(contact_info contact);

int main() {person1.name = "Michael";person1.age = 22;person1.address = "23 Emerson st. Hamilton";person2.name = "Sam";person2.age = 21;person2.address = "23 Emerson st. Hamilton";

printContact(person1);cout << endl;printContact(person2);return 0;

}void printContact(contact_info contact) {

cout << "Name: " << contact.name << endl;cout << "Age: " << contact.age << endl;cout << "Address: " << contact.address << endl;

}

Wenqiang Chen Object Oriented Programming in c++

Page 6: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

What are classes?

Specify the form(blueprints) of an object

Combines data representation and methods for manipulatingthat data into one neat package

data and functions within a class are called members of theclass.

Wenqiang Chen Object Oriented Programming in c++

Page 7: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Defining and using classes

class Box{public:

double length;double width;

};int main(){

Box box1;Box box2;box1.length = 2;box1.width = 3;

}

Wenqiang Chen Object Oriented Programming in c++

Page 8: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Definition: Functions that are members of a class(belongs to theclass).

Can be defined within the class definition or outside of classusing scope resolution operation(”::”)

Has access to all members of the class

Wenqiang Chen Object Oriented Programming in c++

Page 9: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Member function definition

#include <string>#include <iostream>using namespace std;class Box {

public:double length;double width;void printShape();

};int main() {

Box box1;box1.printShape();

}void Box::printShape() {

cout << "square";}

Wenqiang Chen Object Oriented Programming in c++

Page 10: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Access Modifier and scope

Access public protected private

Same class yes yes yesDerived classes yes yes noOutside classes yes no no

Wenqiang Chen Object Oriented Programming in c++

Page 11: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Modifier example

class Box{

\\public variables and member functionspublic:

double length;void setWidth( double wid );double getWidth( void );

\\private variablesprivate:

double width;\\protected variablesprotected:

double height;};

Wenqiang Chen Object Oriented Programming in c++

Page 12: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Constructor

A class constructor is a special member function of a class that isexecuted whenever we create new objects of that class.

Must have exact same name as the class.

Must not have any return type.

Useful for setting initial values for certain member variables.

Allows overloading.

Constructor can call other Constructor (Constructordelegation).

Cannot use Constructor like other member function. e.g.ClassName.Constructor()

Wenqiang Chen Object Oriented Programming in c++

Page 13: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Constructor example

#include <string>#include <iostream>using namespace std;class Box {public:

Box(); //ConstructorBox(double len, double wid);double length;double width;

};int main() {

Box box1;Box box2(23,42);

}Box::Box() {

cout << "box is created." << endl;}Box::Box(double len, double wid) : length(len), width(wid) {

cout << "box of " << length << " and " << width << " is created." << endl;}

Wenqiang Chen Object Oriented Programming in c++

Page 14: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

A destructor is a special member function of a class that isexecuted whenever an object of it’s class goes out of scope orwhenever object is ”deleted”.

Must have exact same name as the class prefixed with a tilde( )

Cannot return a value or take any parameters.

Contains code to delete all dynamic variables created by theobject.

A class can only have 1 Destructor.

Wenqiang Chen Object Oriented Programming in c++

Page 15: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Destructor example

#include <string>#include <iostream>using namespace std;class Box {

public:Box(); //Constructor~Box(); //Destructorstring *str = new string;double length;double width;

};int main() {

Box box1;}Box::Box() {

cout << "box is created." << endl;}Box::~Box(){

delete str;cout << "string is deleted" <<endl;cout << "box is deleted" << endl;

}

Wenqiang Chen Object Oriented Programming in c++

Page 16: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Encapsulation

Bundling data and functions and exposing only the interfaces(hiding the implementation details) to the user.

Using access modifiers : private, protected and public

Ok to make everything private.

Wenqiang Chen Object Oriented Programming in c++

Page 17: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Function Overloading

Have multiple definitions for the same function name in thesame scope

Definition of the function must differ from each other by thetypes and/or the number of arguments in the argument list

Cannot overload function declarations that differ only byreturn type. e.g. void print() vs int print();

Wenqiang Chen Object Oriented Programming in c++

Page 18: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Function overloading example

#include <string>#include <iostream>using namespace std;class Box {public:

Box();void enlarge();void enlarge(double l, double w);double length;double width;

};

int main() {Box box1;box1.enlarge();box1.enlarge(20,20);

}Box::Box() {

length = 2;width = 2;

}void Box::enlarge() {

length++;width++;cout << "new size: " << length << " " << width << endl;

}void Box::enlarge(double l, double w) {

length+=l;width+=w;cout << "new size: " << length << " " << width << endl;

}

Wenqiang Chen Object Oriented Programming in c++

Page 19: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Operator Overloading

Redefine or overload most of the built-in operators

Allows you to use operators with custom types.

defined using keyword ”operator” followed by the symbol forthe operator being defined

Overloaded operator has a return type and a parameter list.

Wenqiang Chen Object Oriented Programming in c++

Page 20: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Member FunctionsAccess ModifierConstructorDestructorEncapsulationOverloading

Operator overloading example

#include <string>#include <iostream>using namespace std;class Box {public:

Box ();Box operator+(const Box& box2){

Box box;box.length = this->length + box2.length;box.width = this->width + box2.width;return box;

}double length;double width;

};int main() {

Box box1;Box box2;Box box3 = box1 + box2;cout<< box3.length <<" " << box3.width <<endl;

}Box::Box() {

length=2;width=2;

}

Wenqiang Chen Object Oriented Programming in c++

Page 21: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

InheritanceRedefining functionsconstructor and destructor in derived class

Inheritance

Inheritance is the process by which a new class(derived class) iscreated from another class(base class)

Derived class automatically has all the member variables andfunctions of the base class

Derived class can have additional member variables and/ormember functions

The derived class is a child of the base or parent class

Can derive multiple base class

Wenqiang Chen Object Oriented Programming in c++

Page 22: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

InheritanceRedefining functionsconstructor and destructor in derived class

Defining inheritance

class Box {public:

double length;double width;

};class Crate: public Box {public:

double height;};class ColorCrate: public Crate{public:

string color;};

Wenqiang Chen Object Oriented Programming in c++

Page 23: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

InheritanceRedefining functionsconstructor and destructor in derived class

Derived class has the option to redefine member functionsinherited from base class

Only redefine functions as needed .

Derived class can have additional member variables and/ormember functions.

The derived class is a child of the base or parent class.

Can derive multiple base class.

Destructor, Copy Constructor, assignment operators are notinherited.

Base class member function can still be called by usingDerivedClass.BaseClass::function

Wenqiang Chen Object Oriented Programming in c++

Page 24: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

InheritanceRedefining functionsconstructor and destructor in derived class

Redefining functions example

class Box {public:

Box();void enlarge();void enlarge(double l, double w);double length;double width;

};class Crate: public Box {public:

void enlarge();};

Wenqiang Chen Object Oriented Programming in c++

Page 25: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

InheritanceRedefining functionsconstructor and destructor in derived class

constructor and destructor in derived class

Default constructor of base class is automatically called whenderived class is created (unless explicitly call other constructor).

Constructor are called in a Top to Bottom order (Parent to Child).

Destructor are called in a Bottom to Top order (Child to Parent).

Wenqiang Chen Object Oriented Programming in c++

Page 26: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

InheritanceRedefining functionsconstructor and destructor in derived class

Derived Constructor example

#include <iostream>using namespace std;class Box {public:

Box();double length;double width;

};

class Crate: public Box {public:

Crate();double height;

};

class ColorCrate: public Crate {public:

ColorCrate();string color;

};int main() {

ColorCrate c;}Box::Box() :length(0), width(0) {

cout << "box is created" << endl;}

Crate::Crate() :height(0) {

cout << "crate is created" << endl;}

ColorCrate::ColorCrate() {cout << "color crate is created" << endl;

}

Wenqiang Chen Object Oriented Programming in c++

Page 27: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

PolymorphismVirtual FunctionVirtual DestructorExample

Polymorphism

Refers to the ability to associate multiple meanings with onefunction name using a mechanism called late binding

Polymorphism is a key component of the philosophy of objectoriented programming

Call to a member function will cause a different function to beexecuted depending on the type of object that invokes thefunction.

Wenqiang Chen Object Oriented Programming in c++

Page 28: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

PolymorphismVirtual FunctionVirtual DestructorExample

Declared using keyword ”virtual”.

Signals to the compiler that we don’t want static linkage forthis function.

Allows late binding.

Wenqiang Chen Object Oriented Programming in c++

Page 29: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

PolymorphismVirtual FunctionVirtual DestructorExample

Virtual destructors

Destructors in derived class should be virtual.

why?

Because destructor of the derived class automatically callsdestructor of the base class.

Apply this with polymorphism.

e.g. when you delete base class Box, it calls destructor of derivedclass, which then calls destructor of base class

Wenqiang Chen Object Oriented Programming in c++

Page 30: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

PolymorphismVirtual FunctionVirtual DestructorExample

Polymorphism example

#include <iostream>using namespace std;class Box {public:

Box();virtual void print()=0;double length;double width;virtual ~Box();

};

class Crate: public Box {public:

Crate();virtual void print();double height;virtual ~Crate();

};

class ColorCrate: public Crate {public:

ColorCrate();virtual void print();string color;virtual ~ColorCrate();

};int main() {

Box *b = new ColorCrate;

b->print();delete b;

}

Box::Box() :length(0), width(0) {

cout << "box is created" << endl;}

Wenqiang Chen Object Oriented Programming in c++

Page 31: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

PolymorphismVirtual FunctionVirtual DestructorExample

Polymorphism example cont.

Box::~Box() {cout << "box is created" << endl;

}Crate::Crate() :height(0) {

cout << "crate is created" << endl;}Crate::~Crate() {

cout << "crate is deleted" << endl;}void Crate::print() {

cout << "This is a crate" << endl;}

ColorCrate::ColorCrate() {cout << "color crate is created" << endl;

}

ColorCrate::~ColorCrate() {cout << "color crate is deleted" << endl;

}

void ColorCrate::print() {cout << "This is a colorful crate" << endl;

}

Wenqiang Chen Object Oriented Programming in c++

Page 32: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Header filesCompiling multiple .cpp files

Header

Separate class declaration and actual definition of class.Box.h

#ifndef BOX_H_#define BOX_H_

class Box {public:Box();void print();double length;double width;~Box();

};#endif /* BOX_H_ */

Box.cpp#include <iostream>#include "Box.h"using namespace std;Box::Box():length(0),width(0){

cout<<"Box is created";}void Box::print(){

cout<<"This is a box";}

Box::~Box(){

}int main(){

Box b;}

Wenqiang Chen Object Oriented Programming in c++

Page 33: Object Oriented Programming in c++ · Compiling multiple .cpp les Wenqiang Chen Object Oriented Programming in c++. Structure Classes & Objects Inheritance Polymorphism Additional

StructureClasses & Objects

InheritancePolymorphism

Additional contents

Header filesCompiling multiple .cpp files

To compile project with multiple cpp files:run : g++ Class1.cpp Class2.cpp Class3.cpp ....Classn.cpp -ooutput.exe

Wenqiang Chen Object Oriented Programming in c++