A Note for SE 116 Introduction to C++ Programming S. Kondakcı Composed from the text...

117
A Note for SE 116 Introduction to C++ Programming Composed from the text “Object- oriented Programming With C++”, S. S. Kondakcı Kondakcı http://homes.ieu.edu.tr/~skonda kci

Transcript of A Note for SE 116 Introduction to C++ Programming S. Kondakcı Composed from the text...

A Note for SE 116 Introduction to C++ Programming

Composed from the text “Object-oriented Programming With C++”, S. KondakcıS. Kondakcı

http://homes.ieu.edu.tr/~skondakci

Displaying on the screen: Displaying on the screen: coutcout

#include <iostream>#include <stdio.h>

int main(){int x = 200;char *hello = “Hello my world!”;cout << x; send 200 to displaycout << hello;cout <<”My dearest cat”;printf(”My dearest cat”);printf (”\n”);cout <<’\n’;return 0; }

#include <stdio.h>int main(){int x = 200;char *hello = ”Hello my world!”;printf(“%d”,x);printf(“%s”,hello);printf(“My dearest cat”);printf (“\n”);return 0;}

Cout: prints on the standard output (screen)

C++ Version C version

Reading from the Keyboard: Reading from the Keyboard: cincin

#include <iostream>using std::cout;using std::cin;int main(){int x;char hello[45];cout <<”Enter an int: “;cin >> x;cout <<”Enter a text: “;cin >> hello;return 0;}

#include<stdio.h>int main(){int x;char *hello;printf(”Enter an int: “);scanf(“%d”, &x);printf(”Enter a text: “);scanf(“%s”, hello);return 0;}

Cin: reads from the standard input (keybord)

C++ Version C version

CChained input and output operationshained input and output operations include <iostream>using std::cout;using std::cin;int main(){int x, y,i;char *hello, foo;

cin >> x >>y; // Chained inputcin >>hello>>foo;return 0;

} include <iostream>using std::cout;using std::cin;int main(){

int x = 200; float y= 3.14;char *hello = “Hello my world!”;cout <<“An integer “<< x<< “ a float ” << y;cout <<“A character string “<< hello<<’\n’; return 0;

}

• Input and the output can be formatted by manipulators

• Manipulators permanently change the state of the stream to which is applied (except setw)

– For example placing “hex” in the output stream causes all subsequent output of ints, shorts, longs to be written in hexadecimal format

int a=19;cout<< a; // 19cout<<hex<<a; // 13

• Manipulators without arguments require iostream file, manipulators with arguments require iomanip header file

CS116 SENEM KUMOVA METİN

Oo Programming/S. Kondakci 6

Basic Manipulators

Manipulator Purpose Example

endl Write newline and flush stream cout <<endl;ends Write ’\0’ terminator in stream ostream str;str <<ends;elush Flush output stream cout << flush;setbase(int n) Set integer base to n cout << setbase(16);setfill(char c) Set fill character to c cout << setfill(‘*’);

Some manipulators in C++• endl write a newline

• dec input or output in decimal• oct input or output in octal • hex input or output in

hexadecimal

• fixed use fixed notation for floating point numbers: d.ddd• scientific use scientific notation for floating point numbers• left left justify• right right justify

• setfill(c) make c to fill character• setprecision(n) set floating point precision to n• setw(n) set field width to n

• others are in your textbook !!!

Need iomanip header file

#include<iostream>

using namespace std;

main(){

int i=10;cout<< "i= "<< i <<" (decimal)\n";cout<< "i= "<< octoct <<i <<" (octal)\n";cout<< "i= "<< hexhex<< i <<" (hexadecimal)\n";

cout<< "i= "<< i <<" (? ? ?)\n";cout<< "i= "<<decdec<< i <<" (decimal)\n";

}

CS116 SENEM KUMOVA METİN

Example2 : Manipulators#include <iostream> #include <iomanip>

using namespace std;

int main() {

int num1 = 12, num2 = 345, num3 = 6789;

cout << endl; //Start on a new line

cout << setw(6) << num1 << endl<< setw(6) << num2; cout << endl <<setfill('*') << setw(10) <<num3; //Output 2 * followed by 6789

cout << endl; //Start on a new line return 0; //Exit program

}

Oo Programming/S. Kondakci 10

Format Outputs With Manipulators

Some iostream output formatters are:

width() Return the field width

width(int) Change the field width and return the old field

fill() Return the fill character

fill(char) Change the fill character and return the old fill char.

precision() Return the precision for floating point numbers

precision(int) Change the precision and return the old precision

Formatted output capabilities of C can be also used together within any C++ code.

Oo Programming/S. Kondakci 11

Example: Formatted Output #include<iostream>

using namespace std;

cout.width(3);cout << "ABCDE";

cout.width(3); cout <<"F" <<"G";

ABCDE Output shown on the screen

FG

cin.width(3);

cin >> str; // Puts only chars and \0 into str

cout.width(5); // Reserve 5 char spaces

cout.fill(‘-’); // Fill the rest with -

cout << "AA";

---AA Output shown on the screen

cout.width(5); // Reserve 5 char spaces

cout.fill(’-’);//Fill the rest with - before print

cout << "AA";

cout.width(8);cout << "BB";cout.fill('*');

  ---AA******BB Output shown on the screen

cout.precision(2);

cout<< 45.2395987;

Oo Programming/S. Kondakci 12

Formatting Output With setf()and Format Flags

The setf() function can be used to perform a number of operations:

left-justify,

right-justify,

specify base for an integer output,

specify scientific or fixed point output,

specify precision for floating point outputs

Oo Programming/S. Kondakci 13

Format Flags skipw Skip white space

left Left-justify

right Right-justify

dec Decimal (base 10)

oct Octal (base 8)

hex Hexadecimal (base 16)

showbase Show base indicator on output

showpoint Output trailing zeros in floating-point numbers

uppercase Use uppercase letters on hex output

showpos Show + with positive integers

scientific Use scientific notation (d.dEd)

fixed Use fixed notation for floating-point numbers

internal Padding after sign or base flag

unitbuf Flush any stream after write

stdio Flush standard output and standard error after write

Oo Programming/S. Kondakci 14

How to Use Format Flags

Function setf() with one argument will set the specified format flag

Function flags() can be used to set a flag specifier,

function unsetf() is used to clear a specified flag

Examples:

cout.setf(ios::uppercase); // Uppercase from now on

cout.setf(ios::oct, ios::basefield); /* Set the integer base to octal base on the standard output use */

cin.unsetf(ios::skipws); // Not skip white spaces

cin.setf(ios::skipws); // Skip white spaces

Oo Programming/S. Kondakci 15

Examples:Format Flags

cout.setf(ios::left, ios::adjustfield); // Output left justified

cout.setf(ios::right, ios::adjustfield); // Output right justified

cout.setf(ios::dec, ios::basefield); // Output base 10 (decimal)

cout.setf(ios::oct, ios::basefield); // Output base 8 (octal)

cout.setf(ios::hex, ios::basefield); // Output base 16 (Hexadecimal)

cout.setf(ios::scientific, ios::floatfield);

// Output floating point numbers in scientific notation

cout.setf(ios::fixed, ios::floatfield);

// Output floating point in fixed-point format

Oo Programming/S. Kondakci 16

Examples:Format Flags

cout.setf(ios::hex,ios::basefield); // Set format for hex output

cout << "Hex: " << 168 << endl; // Outputs Hex: a8

cout.setf(ios::oct, ios::basefield); // Set format for octal output

cout << "Octal: " << 168 << endl; // Outputs Octal: 250

cout.setf(ios::showbase|ios::uppercase); //Indicate uppercase hex

cout.setf(ios::hex,ios::basefield); //Set hex output format

cout << "Hex: " << 168 << endl; // Outputs Hex: 0XA8

Namespace Usage 1

// Declaring a namespace

#include <iostream>

namespace myStuff { int value = 0; }

int main() {

std::cout << "\nDefined as " << myStuff::value << std::endl;std::cout << "enter an integer: "; std::cin >> myStuff::value; std::cout << "\nYou entered " << myStuff::value << std::endl; return 0;

}

Namespace Usage 2

// Declaring a namespace

#include <iostream> namespace myStuff { int value = 0; } using namespace std;using namespace myStuff;int main() {

cout << "enter an integer: "; cin >> value; cout << "\nYou entered " << value << endl; return 0;

}

Namespaces• C++ provides namespaces to prevent name conflicts…• Namespace std includes standard C++ function, e.g., cout, cin,endl, etc

namespace xxx { int flag; int s;}namespace yyy { int flag; int s;}

main(){ xxx::flag=3; // :: is the scope resolution operator yyy::flag=-1; }

// with a using declarationnamespace xxx { int flag; int s;}namespace yyy { int flag; int s;}using xxx::flag;

main(){ flag=3; // xxx::flag=3; xxx:: s=0; yyy::flag=-1; yyy:: s=1; }

// using namespace // declaration covers entire namespacenamespace xxx { int flag; int s;}namespace yyy { int flag; int s;}using namespace xxx;

main(){ flag=3; s=0; // xxx::s=0; yyy::flag=-1; yyy:: s=1;

cout<<flag; cout<< yyy::flag; }

Boolean Data Type boolbool

• Boolean data type takes values either “true / 1” or “false / 0”• The keyword for declaring boolean variables is bool

#include<iostream>using namespace std;

int main(){

bool flag ;flag= (3<5); // will return a 1 = truecout <<flag<<endl;cout<<boolalpha <<flag <<endl; // prints “true”

return 0;}

20

Enumerate Your Own Data Types: enum {...};Enumerate Your Own Data Types: enum {...};

Enumerated types are declared using the enum keyword

#include<iostream>using namespace std;

int imain(){ // declaration of type

enum days { Sunday,Monday,Tuesday,Wednesday,Thursday,friday,Saturday};

days today, tomorrow;today=sunday;tomorrow= monday;cout <<today<<endl; // prints 1cout <<tomorrow<<endl; // prints 2 return 0;

}

21

C++ StructuresC++ Structuresstruct Point {

double x;double y;void setVal (double xval,double yval) { x = xval; y = yval;}

} ;• In C struct Point p1;

p1.x=9;

• In C ++ Point p1 p1.x=9;

p1.setVal(3.2 , 5.4);// use member selector operator to reference p1’s data members and

function members

22

The string Data TypeThe string Data Type• Strings in C++ are null terminated char arrays in C• you have to include header string

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

main(){string s1 = "HELLO";string s2 = s1;string s3 (10,'x'); // a string consisting of 10 x’s

cout<< s1 <<endl <<s2 <<endl <<s3 << endl;cout<< s1.length() << endl; // will return a 5

cin >> s1; cout << s1 <<endl;}

23

Converting C++ strings to C StyleConverting C++ strings to C Style

// Sometimes wou will need C type strings // (null terminated arrays of char)

#include <string>#include<cstring> // strcpy()#include<cstdio> // printf()using namespace std;

int main(){

char cstr[20];string str ("Hello World");strcpy(cstr, str.c_str());printf("%s",cstr); // c_str() function returns a

// pointer to C style strings return 0;

}

24

Other String Functions: Erasing and InsertingOther String Functions: Erasing and Inserting

• Erasing :

string s = “Ray Dennis Steckler”;s.erase(4, 7);//find the substring beginning at index 4 of

// length 7 and erase itcout<<s; // Ray Steckler

• Inserting :

string s1 = “Ray Steckler”;string s2=“Dennis”;s1.insert(4,s2); // first arg. is the index where insertion begins

//and second arg. is the string to be inserted

cout<<s1<<endl;

25

Searching strings in substringsSearching strings in substrings

// Function find will return the index// where it finds s2 or will retun + infinity // if it cannot find

string s1=“Ray Dennis Steckler”;string s2=“Dennis”;int f;f=s1.find(s2); // f= 4

27

Comparing StringsComparing Strings

string s1=“equlibrium”;string s2=“equalizaiton”;

if(s1==s2) cout <<“equal\n”;else cout << “not equal\n”;

if(s1!=s2) cout <<“not equal\n”;else cout << “equal\n”;

if(s1<s2) cout<<“less than\n”;else cout<<“not less than\n”

if(s1>s2) cout<<“greater than\n”;else cout<<“not greater than\n”);

28

IntroductionIntroduction To To Object-oriented Object-oriented programming programming

• Object-oriented programming (OOP) – Encapsulates data (attributes) and functions (behavior) into

packages called classes

• Information hiding – Class objects communicate across well-defined interfaces

– Implementation details hidden within classes themselves

• User-defined (programmer-defined) types: classes– Data (data members)

– Functions (member functions or methods)

– Similar to blueprints – reusable

– Class instance: object

BasBasiic c Object-orientd Object-orientd Concepts Concepts

1- Universe = Problem domain

2- Class = Abstract definition of an overall structure

3- Object = Instance of classess

4- Members = Elements of a class representing both operations and data used for solving the problem

a) Data members

b) Functin members (Methods)

5- Messages = Invoke methods

The Universe and Classes of a Car Factory

UniverseCar factory

Empl_NEmpl_1 Empl_2

EmployeeObjects

Car_1 Car_2 Car_N

Carobjects

Details of the Details of the Objects of the Car Objects of the Car FactoryFactory

 Car Objects:

Data members Methods (Function members)-------------------- -----------------------Model, display_car_data()Number of seats, get_car_data()Color set_car_colour()

test_car()  

Employee Objects:Data members Methods (function members)------------------ -----------------------Name, register_emp(),Address, delete_emp(),phone_nr, move_emp(),section,birth.

Class Scope and Accessing Class Members

• Class scope – Data members, member functions

– Within class scope• Class members

– Immediately accessible by all member functions

– Referenced by name

– Outside class scope• Referenced through handles

– Object name, reference to object, pointer to object

• File scope – Nonmember functions

Class Scope and Accessing Class Members

• Function scope– Variables declared in member function

– Only known to function

– Variables with same name as class-scope variables• Class-scope variable “hidden”

– Access with scope resolution operator (::)

ClassName::classVariableName

– Variables only known to function they are defined in

– Variables are destroyed after function completion

Member Access Specifiers

• private: The keyword states that the following members are accessible to members and friends ONLY. Friends are methods that can be accessed by foreign classes.

• public: The keyword states that the members following after public keyword are accessible to general public. That is, members following the keyword public can be accessed by any variable defined elsewhere in the program.

• protected: Members definitions following the keyword protected are accessible to members and friends, and to members and friends of subclasses only.

Defining and Using ClassesDefining and Using Classes

class Customer{ private: char name[32], addr[128]; long tlf; credit kredi; public: // Only the prototype definition void enter(); void delete(); void change(); void find_and_show();};void Customer:: enter(){

cout << “\n Enter the name: ”;cin.getline(name, sizeof(name), ‘\n’);cout << “\n Enter the phone number: ”;cin >> tlf;// and so on ...

}

int ain() { Customer c1, c2, c3;

Customer c[3];c2.enter(); c[1].enter(); c2.change();return 0;

{

Get and Set FunctionsGet and Set Functions

• For convenience we can define set() and get() functions for handling any data type we want:

class A{ int a, int b;

sting s1, s2; // declare functions as publicpublic: // ..

int add(int x, int y);string concatenate(string sx, sy);void set_s1(string s){s1 = s;}void set_s2(string s){s2 = s;}

int getInt(int k){return k;}string getStr(string ss) {return ss;}

void seta(int n){a=n;}void setb(int n){b=n;}

};

Scope Resolution Operator (::)Scope Resolution Operator (::) #include<iostream>using namespace std;int x = 9; // Global x. This x is from the file scope class x_plus_y {

int x; // local data member x. This x is from the class scope.int y; // local data variable member y

public:void add(int x, int y) //Define function member add(){

cout <<"Result of local x + y = "<< ::x + y<<endl; //Global x + y

int result = x + y; // Local x + ycout << "The result is: " << result << endl;

}}; // End of class declarationint main() {

int a = 1;int b = 3;x_plus_y sum; // Create an instance of x_plus_y

x = ::x+a; // local x = 9 + 1, that is global x + a = 10. sum.add(a,b); // Displays first 13 (10 + 3)// and then display “The result is: 4”

return 0;}

Constant Data Typesclass Car {private: int speed, model;public: Car (int sp, int mod) {

// Car constructor speed = sp; model=mod; }

void display() const; // const member function prototypevoid disp2();

 };void Car::display() const; // const member function{ cout <<"Model: " <<model <<endl; cout <<"Speed: " <<speed <<endl;}

void Car::disp2() {

// non-const member function

cout <<"Model: " <<model <<endl;

cout <<"Speed: " <<speed <<endl;

}

int main(void) {

const int x = 10; // Integer const

const Car myCar(220, 2013);

// myCar Object is constant

Both int x and myCar are now unmodifiable.

const Car myCar(260,200); // Create a const obj myCar.display(); //correct usage

myCar.disp2();//Wrong! Error generated by comp

// create another non-const Car object

Car anotherCar(220,2004);

anotherCar.disp2(); // correct

anotherCar.dispplay(); //ALSO CORRECT!

return 0;

}

Object Initialization: (Wrong way!)include<iostream>include<stdio.h>using std::cout; using std::cin; class Car{

private: int model; unsigned char brand[12],plaka[12];

public: void get_car_data(); void disp_car_data(char *c);

void init1(Car *p); void init2();

};void Car::init1(Car *p){

p->model=1996; strcpy(p->plaka,NULL);

strcpy(p->brand,"Anadol");}void Car::get_car_data(){

char dummy[10];cout <<"\nType the model: ";cout.flush();cin >> model;cout <<"\nType the Plate number: ";cout.flush(); cin >> dummy;cin.getline(plaka,12,'\n');cout <<"\nType the brand: ";

cout.flush();cin.getline(brand,12,'\n');

}

void Car::disp_car_data(char *c){cout << "\nModel: " << model;cout << "\nPlate Number: " << plaka;cout << "\nBrand: " << brand;}void Car::init2(){ model=1996; strcpy(plaka,"06 ank 96"); strcpy(brand,"Murat");}

int main(){Car mycar, your_car;your_car.init2();your_car.disp_car_data("Your_car after init2()");mycar.get_car_data();mycar.disp_car_data("Mycar after get_car_data()");Car *ptr; // Create pointer ptr ptr = new Car; //create a new car object, let ptr to point at it.ptr -> init1(ptr);ptr->disp_car_data("After ptr->init1(ptr)");mycar.init1(ptr);//mycar has the same members as with get_car_data()mycar.disp_car_data("After mycar.init1(ptr)");delete ptr;}

Object Initialization: ConstructorsConstructors (The correct way of object initialization!)

• Constructor function– Special member function

• Initializes data members

• No return type

• Share the same name with the class

– Called implicitely when object instantiated

– Several types of constructors• Default constructor

• Parameterized

• Copy constructor

• Convert constructor

Many Ways of Defining Constructors

class my_class {int x, y;

public:my_class() {// Default constructor x=5; y=10; }my_class(int a, int b){ // Parameterized constructor

x = a; y = b;}// These are also parameterized constructors

// my_class(int a, int b): x(a), y(b) {}// my_class(int a,int b): x(a) {y = b;}};int main() { my_class cl1, ; // Object created with default values: x=5, y=10 my_class cl2(20,30); // Parameters during object creation my_class cl3(40,50); // Parameters during object creation my_class cc,dd,ee,ff; my_clas many_objects[1000]; return 0;}

Copy Constructors: Object Instantiation With Existing Objects

int main(){ my_class my_object(10,20); // create an instance of my_class

my_class your_object(my_object); // This copies values from my_object return 0;}

Static Data Typesclass Car {private: int speed, model;public: static int numberOfCars; Car (int sp, int mod=1996) // Constructor { speed = sp; model=mod; new_car(); } static void new_car() {

numberOfCars++; }};int Car::numberOfCars=0;int main(void){ Car c1(220);c1.display(); return 0;}

This static var is shared by all of the objects

•It must be initialized only once in file scope

•If foreign class will access it then the class must be defined as friend.

Example: Using Static Members#include<iostream>using namespace std;class my_class {

int x, y; public:

void setNumbers(int a, int b){x =a; y = b;} // setter functionint GetX() const { return x;} // getter function for xint GetY() const {return y;} // getter function for ystatic int count; // static data membermy_class() {// Default constructor setNumbers(10,20); count++; // Static variable must be initialized outside }static int getCount() {// Must use static function to access static data members return count;}

};int my_class::count = 0;// static variables must be initialized befor object creation int main() { my_class cl1; // Object created with default values: x=5, y=10 cout<<"Value of X: "<<cl1.GetX()<<endl; cout<<"Value of Y: "<<cl1.GetY()<<endl; cout<<"Value of static variable: "<<cl1.getCount()<<endl; my_class::count--; // Use this to access the class member too! cout<<"Value of static variable: "<<my_class::getCount()<<endl; return 0;}

Example: Parameterized Constructors

#include<iostream>#include<cstring> // This is for strcpy()using namespace std;class my_string {

char *str;int a;

public:my_string() { // Default ctor

a = 20;str = new char[20]; // Allocate memorystrcpy(str,"Hello Friend!");

}my_string(int length);void disp(){

cout<<"Int member a: "<<a<<endl;cout<<"String member str: "<<str<<endl;

}}; // End of class declarationmy_string::my_string(int length){

a = 500;str = new char[length]; // Allocate memorystrcpy(str,"Hello World!"); // Initialize

}int main() {

my_string ms1; my_string ms2(15);ms1.disp(); ms2.disp();return 0;

}

Destructors

class String {char *str;

int len;public:

String (const char *, const char *);~String() { delete [] str};

};String::String (const char *s, const char *){

len = strlen(s);str = new char[len + 1 ];assert (str != 0);strcpy(str,s);

}

Destructors:

• Release the resources that the constructor may have allocated.

• Are automatically executed when an object goes out of existence

More Constructorsenum col {red,yellow,green}; Class Color {

col r, g, y;public:

Color() // default constructor{

r = red; g=green; y=yellow;}

// Parameterized constructorColor(col rgy){

r=g=y=rgy;}

}; int main(){

Color three_color;Color one_color(red); // Object is red

}

Copy Constructor

Class Color {col r, g, y;

public:Color() // default constructor{

r = red; g=green; y=yellow;}Color (Color&) // Copy constructor

};Color::Color(Color& C){ r=C.r;y=C.yg=C.g;}int main() {

Color C1; // Default constructorColor C2(C1); // Copy constructorColor c3(C2); // Copy agin-and-again

}

Convert Constructors

#include<iostream>

using namespace std;

class Clock {int hour, min;bool ap;

public:Clock() { // sets the default time to 12:00 AM hour = 12; min = 0; ap = false;}Clock(int);void show_time();

};

Convert Constructors

Clock::Clock(int time){ min = time % 100; hour = time / 100; if (hour > 12 ) {

hour -= 12;ap = true;

elseap = false;

}void Clock::show_time()// print time as hh:mm: XX{

cout << setfil(‘0’) << setw(2) << hour<< ‘:’ << setw(2) << min << setfill(‘ ‘);

if (ap)cout << “PM”;

elsecout << “AM”;

cout << endl;}

Using the Convert Constructors

int main() {//first convert 1410 to hour = 02, and min = 10// then copy them to object cc and display as 02:10 PM

Clock cc = Clock (1410); cc.show_time();

// or You can also use a cast to Clock Clock cc = (Clock) 123;cc.show_time();//That will display 01:23 AM.

// Implicit type conversion is also possible: Clock cc = 1050;cc.show_time();// That will display 10:50 AM return 0;}

ReferenceReference Variable Variables and Reference Parameterss and Reference Parameters

Two ways to pass arguments to functions in many programming languages are pass-by-value and pass-by-reference.

When an argument is passed by value, a copy of the argument’s value is made and passed (on the function call stack) to the called function. Changes to the copy do not affect the original variable’s value in the caller.

With pass-by-reference, the caller gives the called function the ability to access the caller’s data directly, and to modify that data if the called function chooses to do so.

©1992-2010 by Pearson Education, Inc. All Rights Reserved.

What is a Reference? Name of memory locationWhat is a Reference? Name of memory location

Reference is denoted by the at (or ampersand) sign & and provides an alternative name for storage

int x;int & ref = x;x = 3;ref = 3; // same as x = 3

54

x … ref

3

Call by Reference : SWAP exampleCall by Reference : SWAP example

#include <iostream>using namespace std;

void swap (int &, int &);

void main(){int i=7 ; int j=-3;swap (i,j);cout << i <<endl;cout << j << endl;

}

void swap (int & a, int & b) {int t = a;a = b;b = t;

}

55

Return by Value Return by Value

int val1() {int i=8;

… return i;

}main(){

int t;t = val1(); // The value t is returned from val1()

…}

56

8 8 8i

Copy to Copy to

temporary storage t

Functions Functions RReturning Returning References eferences

• Returning references from functions can be dangerous.

• When returning a reference to a variable declared in the called function, the variable should be declared static within that function.

• Otherwise, the reference refers to an automatic variable that is discarded when the function terminates; such a variable is “undefined,” and the program’s behavior is unpredictable.

• References to undefined variables are called dangling references.

©1992-2010 by Pearson Education, Inc. All Rights Reserved.

Return by Reference Return by Reference

int & val1() {int i=8; return i;

}main(){

int t;t = val1();

…}

58

8it

NO TEMPORARY STORAGE IS USED !!! t IS NOW i

DANGER: val1 returns a reference to a value that is going to go out of scope when the function returns. The caller receives a reference to garbage. Fortunately, your compiler will give you an error if you try to do this.

• References can also be used as aliases for other variables. Once a reference is declared as an alias for a variable, all operations “performed” on the alias (i.e., the reference) are actually performed on the original variable.

• The alias is simply another name for the original variable. • For example, the code

• int count = 1; // declare integer variable countint &cRef = count; // create cRef as an alias for countcRef++; // increment count (using its alias cRef)

increments variable count by using its alias cRef.

©1992-2010 by Pearson Education, Inc. All Rights Reserved.

References as Aliases References as Aliases

Passing and Returning Objects by ValuePassing and Returning Objects by Valueclass Person { public :

void setAge (unsigned n) { age = n;

};unsigned getAge() const {

return age;};

private: unsigned age;

};

Person func1() { Person p;

p.setAge(4);return p; // Returning object

}

unsigned func2( Person y) { // Call by value y.setAge(3);return y.getAge();

}

60

int main() {Person x;cout << x.getAge() << endl;x = func1();// cout << func1().getAge(); ?cout << x.getAge() << endl;cout << func2(x) << endl;cout << x.getAge() << endl;return 0;

}

Passing and Returning Objects by ReferencePassing and Returning Objects by Referenceclass Person { class Person { public :public :

void setAge (unsigned n) { void setAge (unsigned n) { age = n; age = n;

};};unsigned getAge() const {unsigned getAge() const {

return age;return age;};};

private:private: unsigned age;unsigned age;

};};

Person & func3(){Person & func3(){Person p;Person p;p.setAge(4);p.setAge(4);

return p;return p;}}

unsigned func4( Person & y){ unsigned func4( Person & y){ // Call by reference// Call by reference y.setAge(3);y.setAge(3);

return y.getAge();return y.getAge();}}

61

int main() {Person x;cout << x.getAge() << endl;x = func3();cout << x.getAge() << endl;cout << func4(x) << endl;cout << x.getAge() << endl; return 0;

}

Pointer to ObjectsPointer to Objects

class Person { public : void setAge (unsigned n) {

age = n; };unsigned getAge() const {

return age;};

private:unsigned age;

};

void func(Person * ptr){ptr->setAge(5);cout << ptr->getAge() << endl;

}

62

Accessing to an object’s members through a pointer requires class indirection operator “->”

int main() {Person x;x.setAge(4); cout << x.getAge()<< endl;func(&x);cout << x.getAge() << endl;

return 0;}

The The this this PointerPointerclass C {private:

int x;public :

C() {x = 0;}void display() {

cout <<x<<endl; }};

The same as

class C {private:

int x;public :

C() {this->x = 0;}void display() {

cout <<this->x<<endl; }};

63

this pointer• an implicit argument to each of a class’s

non-static member functions.

• allows those member functions to access the correct object’s data members and other non-static member functions.

The Pointer Constant The Pointer Constant thisthis

#include<iostream>using namespace std;class Person {private:

string name; // = this->namepublic :

Person( string & name) { this->name = name; // name = name does NOT work

alonename="Mary"; // name is input parameter

}string getName(){ return name;}

};int main() { string n("Joe");

Person p(n); // If not this->name = name then copy won't work

cout << n << " " << p.getName(); return 0;

}

64

This Pointer Helps Concatenating Calls

class Point {

public:

void setX(int x) {_x = x;}

void setY(int y) {_y = y;}

void doubleMe()

{

        _x *= 2;

        _y *= 2;

}private:    int _x;

    int _y;

};

To use this class, we could

write something shown below

Point lower;lower.setX(20);

this.setX(20);lower.setY(30);lower.doubleMe();

Instead we concatenate the calls.

lower.setX(20).setY(30).doubleMe();

That means that the above expression is evaluated from left to right.

((lower.setX(20)).setY(30)).doubleMe();

This Pointer

include <cstdlib>

include <cstdio>

include <ctime>

include <iostream>

 

using std::cout;

 class Sayi {

int x,y;

public:

Sayi(int xx=0, int yy=0)

{

x=xx; y=yy;

}

void randla(int, int);

void display();

};

void Sayi::randla(int Xrand, int Yrand)

{

randomize();x=random(Xrand);

randomize();y=random(Yrand);

}

void Sayi::display()

{

cout <<endl;

cout << "Random X: " << x << endl;

cout << "Random y: " << y << endl;

}

int main()

{

Sayi a(0,1);

a.randla(10,100);

a.display();

return 0;

}

This Pointer class Sayi {

int x,y;

public:

Sayi(int xx=0, int yy=0)

{

x=xx; y=yy;

}

Sayi& randX(int); Sayi& randY(int);

Sayi& display();

};

Sayi& Sayi::randla(int Xrand)

{

randomize(); x=random(Xrand);

return *this;return *this;

}

Sayi& Sayi::randY(int Yrand)

{

randomize(); y=random(Yrand);

return *this;return *this;

}

Sayi& Sayi::display()

{

cout <<endl;

cout << "Random X: " << x << endl;

cout << "Random y: " << y << endl;

return *this;return *this;

}

int main()

{

Sayi a(0,1);

a.randla(10,100).display();

return 0;

}

Class Friends#include<iostream>using namespace std;class Boat; // Forward declaration of class Boat.class Car { private: int model; string brand; public: Car (int a, string br) //Constructor for Car objects. { model=a; brand=br; }friend class Boat; // Boat is now FRIEND to Carstring get_car_brand() {return brand;}};class Boat { private: int model; string brand; public: Boat (int a, string br ) //Constructor for Boat objects. { model=a; brand=br; } int get_model(Car &car_obj) { return car_obj.model;} int get_boat_model(){return model;} string get_boat_brand() {return brand;}};

int main()

{

Car c1(1965, "Anadol");

Boat b1(1990, "Yarali Ceylan");

cout << "Boat object b1 displays Car object c1's model: \t";

cout << b1.get_model(c1) << endl;

/* Access denied with the following statement and compiler

will give error

cout << c1.get_boat_model();

c1 Tries to get and return b1's model but it's not allowed to display the Boats model.

*/

cout << "Boat object b1 displays its own model: \t"; // OK!

cout << b1.get_boat_model(); // b1 displays its own model.

return 0;

}

Functions as Friends: Boat member function is defined to be Car’s friend

class Car; // Make class Car visible to class Boatclass Boat {private: int speed;public: Boat (int sp) {speed = sp; } // Boat constructor int get_car_speed(Car & cobj); }; // End of Boat def.class Car {private: int speed;public: Car (int sp) {speed = sp; } // Car constructor friend int Boat::get_car_speed(Car & cobj); // Friend declaration }; // End of Car def. //This Boat member function can access Car’s private member speed.int Boat::get_car_speed (Car & cobj) { return cobj.speed;}int main() {

Car mycar(90);Boat your_boat(200);int car_speed;car_speed=your_boat.get_car_speed(mycar);cout <<"Car speed: " <<car_speed; cout <<endl; return 0;

}

A non-member function as a friend to Boat and Car class Car {private: int speed;public: Car (int sp) {speed = sp; } // Car constructor friend void show_speed(Car & cobj, Boat & bobj); }; // End of Car def. class Boat {private: int speed;public: Boat (int sp) {speed = sp; } // Boat constructor friend void show_speed(Car & cobj, Boat & bobj); }; // End of Boat def.// This function can access both Car and Boat membersvoid show_speed (Car & cobj, Boat & bobj) { cout << “Car speed: “ << cobj.speed <<endl;

cout << “Boat speed: “ << bobj.speed <<endl;}int main() {

Car mycar(90);Boat your_boat(200);show_speed(mycar,your_boat); cout <<endl;return 0;

}

Inline Functions

void g(){......int z = f()......}

int f(){.........}

void g(){......inline f()......}

Function g() is calling a normal function f() that is defined elsewhere

Function g() is calling an inline function f() that is defined inside g()

Return

Jump

Default ArgumentsDefault Arguments

• C++ allows to specify default values for function parameters.

• When a program omits an argument for a parameter with a default argument in a function call, the compiler rewrites the function call and inserts the default value of that argument to be passed as an argument in the function call.

©1992-2010 by Pearson Education, Inc. All Rights Reserved.

• Default arguments must be the rightmost (trailing) arguments in a function’s parameter list. void f (int v, float s=3.14, char t=‘\n’, string msg =“Error!!”);

• When calling a function with two or more default arguments, if an omitted argument is not the rightmost argument in the argument list, then all arguments to the right of that argument also must be omitted.

Valid invocations: f(12, 3.5, ‘\t’, “OK”);

f(12, 3.5, ‘\t’);

f(12, 3.5);

f(12);

©1992-2010 by Pearson Education, Inc. All Rights Reserved.

• Default arguments can be in the function prototype. void f (int v, float s=3.14, char t=‘\n’, string msg =“Error!!”);

• If the function prototype is omitted, then the default arguments should be specified in the function header in function definition

74

Overloaded Functionsinclude <stdio.h>

 double disp(double x){

printf(“A double number: %f \n”,x);

return x;

}

int disp(int x){

printf(“An integer number: %f \n”,x);

return x;

}

float disp(float x){

printf(“A floating point number: %f \n”,x);

return x;

}

char disp(char x){

printf(“An integer number: %f \n”,x);

return x;

}

int main() {

int m=6;

float n=1.9;

double d=8.89;

char c = “A”;

 

disp(m); // Display int

disp(n); // Diplay float

disp(c);// Display char

disp(d);// Display dooble

return 0;

}

Inheritance: IS A Relationship

Super classor base class

Sub class orderived class

Class animal

Class cats

77

Data Abstraction

 class animal {

private: // private to class animalenum color {red, green, purple, yellow,

black, white, blue, gray}; 

int age;char group[20]; color clr;char race[20];

public: //Public members, accessible to othersvoid display();void enter();

};

78

C++ C++ ImplementationImplementation of Inheritance of Inheritance

class animal {private: // private

int age;char section[20]; //Where in the zoochar race[20];

public:void display();

};  class cats: public animal {

color col;int weight;char owner[128];

};

79

Hierarchical Inheritance

Class animal

class dog class cat class crocodile

leg head color race teeth size

Hierarchicalinheritance

80

Multiple Inheritance

class water_animal class land_animal

class frog

An object can be inherited from many objects

81

Composition: HAS A RelationshipComposition: HAS A Relationship

class leg

class head

class dogouter layer

class headinner layer

class leginner layer

82

Inheritance and Derivation

Subclass (Derived Class) refers to the class derived from a base class Superclass (Base class) refers to the class a subclass derived from Inheritance refers to data members and methods that are

derived to the subclass under derivation. A subclass contains non-private data members and methods of its base class.

 Indirect Inheritance An inheritance hierarchy can be built by

deriving several classes in a chain of hierarchy from a single base class.

83Example of Class Derivation

class Animal { public:

string name;int age;Animal(string name, int a) {

name=s; age = a;}

friend class B; private: string birSır; int ozelFunc() { age =87;}};class Pets : private Animal { public:

int ID; Pets(int id) {ID = id;}

};class Cats : protected Pets { public:

string owner;Cats(string ow){owner = ow;}

};

class Animal

class Pets

class Cats

84Member Accessibility

Private members may be accessed only by methods within its class or by friend functions and friend classes.

Public members are globally accessible. Everyone with appropriate scope can access them.

Protected members may be accessed only within its class hierarchy. Protected members should be used if the class will be used for derivations, otherwise there is no point in having protected members.

Public Inheritance

85

Private Inheritance

86

Protected Inheritance

87

88Member Accessibility in Derived Classes

Defined as in the base class:

Public Protected Private

Public Public in derived class

Protected in derived class

Private in derived class

Protected Protected in derived class

Protected in derived class

Private in derived class

Private Subclass cannot access! Accessed only by use of the base class member functionss.

Subclass cannot access! Accessed only by use of the base class member functionss.

Subclass cannot access! Accessed only by use of the base class member functionss.

Type of Inheritance:

89

Example: Public Inheritance

class Animals { // Base class for animals in a given country public:

int number_of_legs; protected: int weight; private: // Invisible to outside

char *country;};class Cats : public Animals { // class Cats is derived from the class Animals private:

char *color;int age;char *owner;char *name;char *ID;

};

90Example: Private Inheritance

class Base { private:

int sum; public: char *name; protected: int x, y;};class Sub : private Base { private:

int z; public:

int sum(x,y) { return (x + y); } void set_name(char *n) { strcpy(name,n); } void display(){

cout <<name; }

};

91

Example: Protected Inheritance

class Base { private:

int sum; public: char *name; protected: int x, y;};class Sub: protected Base { private:

int z; public:

int sum() { return (x + y); } void set_name(char *nm) { strcpy(name, nm); }

};

92Prtotected Functions And Derived

ClassesProtected functions in base classes become protected in derived classes.The derived class objects cannot invoke the protected member function!

class Base { protected:

char *name;void unset_name() {

delete name;}

  public:void set_name() { name="Butterfly";}void display() { cout <<name <<endl;}

};

class Sub: public Base { protected: int age;};

int main() {

Sub S; Base B;

S.set_name();// Sets name that was inherited from Base

B.unset_name();//*ERROR* Can’t access Base::unset_name()

S.display(); //Displays name that was inherited from Base

S.unset_name()//*ERROR* Can’t access Base::unset_name()

return 0;

}

93Changing Status of Inherited Members

class Base { protected:

int x, y; // x,y become private in the derived class Sub public:

int z; // z becomes private in the derived class Sub};class Sub : private Base{ protected: Base::x; //Reset the access status of x back to protected public: Base::z; // Reset the access status of x back to public;};

Private members are hidden in the derived class: We should pay special attention for accessing them in the derived class.

94Member Accessibility in Derived Classes

Defined as in the base class:

Public Protected Private

Public Public in derived class

Protected in derived class

Private in derived class

Protected Protected in derived class

Protected in derived class

Private in derived class

Private Subclass cannot access! Accessed only by use of the base class member functionss.

Subclass cannot access! Accessed only by use of the base class member functionss.

Subclass cannot access! Accessed only by use of the base class member functionss.

Derived as

95

Name Shadowing (Hiding) Member with same names can be declared both in the base class and in its derived clasess.

LOCALITY RULE:The derived class overshadows (hides) the inheritance of members from the base class with same name. class Base { protected: char * name; public: void set_name() {

strcpy(name,"Butterfly"); } void display() {

cout <<name <<endl; }};class Sub: protected Base { protected: char *name; public: void set_name() {

strcpy(name,"Lion"); } void display() {

cout <<name << endl; }};

int main() {

Base B; Sub S;

B.set_name();

S.set_name();// Sub::name overshadows Base::name

B.display(); cout<<Base::name; cout<<Sub::name;

S.display(); //Displays Lion (Sub::name)

return 0;

}

Will show this on the screen

Butterfly

Lion

96

Inheritance And Constructors

RULES:

•A Base class constructor is always invoked when a derived class object is created.

•If the derived class has its own constructor, then this constructor is also invoked.

•The constructor of the base class handles initialization for the base class members.

• The constructor of the derived class handles the initialization of its own members.

• If the base class contains default constructor then the default constructor will execute automatically each time a derived class object is created.

97Explicit Call to Base Constructor A derived class constructor may explicitly invoke a base class constructor. The explicit call should be made within the declaration of the derived class constructor. The explicit call cannot be made elsewhere!

class Base { protected:

char *name; public: Base() {// Default strcpy(name,”Garga gak”); } Base (const char *n) { // Base Constructor strcpy(name,n); }

void display() { cout <<name <<endl;}

};class Sub: public Base { protected: char *name; public: Sub():Base("Lion") { } Sub(const char *str) // Second Sub constructor {

strcpy(name,str); } void display() {

cout <<name <<endl; }};

int main() {Base B(“Butterfly”); // Base object,

Base::name=ButterflySub S1;// Sub::name=Lion, uses Base constructorSub S2("Eagle"); // Sub::name=Eagle, Sub’s own

constructorS1.display();S2.display();return 0;}

This will display

ButterflyEagle

98

Inheritance Hierarchy And Constructors

In a deep hierarchy, constructors will execute in the following order:

1. Base class constructor

2. First subclass constructor

3. Second subclass constructor

4. Last subclass constructor

99

Hierarchy Example:class Animal { protected:

char name[20];int age;

public:Animal(const char *s, int

a) { strcpy(name,*s); age = a;}

};class Pets:public Animal { protected:

int ID; public:

Pets(int id) {ID = id;}};class Cats:public Pets { protected:

char *owner; public:

Cats(const char *ow){ strcpy(owner,ow);}

};

Cats inherits ID from Pets directly, Cats inherits name and age indirectly through Pets. Because Pets inherits name and age from Animal. These inheritance includes the initialization of the members inherited from the upper level classes. That is, the inherited object Lolly of Cats inherits 23, Home Animal, and 3 through initialization under the creation of the object Lolly.

int main() { Pets Pete(23); Cats Lolly(“Lollita Long”); Animal Pisi(“Home Animal,3); return 0;}

100

Derived class has no constructors

If derived class has no constructors but base class has constructors, then the base class must have default constructor.

Two types of usage of base class constructors:1. Implicit call: The default constructor of the base class executes

automatically whenever a derived class object is created.2. Explicit call: The second case makes use of an explicit call to a base

class constructor in the body of the derived class.

MULTIPLE INHERITANCE :Name Conflicts

#include <iostream>using namespace std;class BC1 {public: void out() { cout << "method in BC1" <<endl;}};

class BC2{public:

void out() { cout << "method in BC2" <<endl;}};

class DC : public BC1, public BC2 {};

int main() { DC d;

d.out(); // AMBIGUOUS. Which out() I want to use? Compiler Error!!d.BC1::out(); // NOW I know which one to use. d.BC2::out(); // Again, I know which one to use.return 0;

}

101

Summary of Destructors

• Destructors are automatically when you an object expires.

• They are called by the system, we cannot call them directly.

• Unlike constructors, they take no arguments• They do not have any return type like regular functions.

102

Destructors under Inheritance

Destructor bodies in an inheritance hierarchy execute in a reverse fashion from Derived class to Base class

103

Destructors under Inheritance:EXAMPLEclass AC {public:

AC() { cout<< " AC::AC() executes \n";}~AC() { cout<< " AC::~AC() executes \n";}

};class BC : public AC {public:

BC() { cout<< " BC::BC() executes \n";}~BC() { cout<< " BC::~BC() executes \n";}

};class CC : public BC {public:

CC(){ cout<< " CC::CC() executes \n"; }~CC(){ cout<< " CC::~CC() executes \n"; }

};

int main() { CC new_object1;

return 0;}

104

Oo Programming/S. Kondakci 105

PolymorophismPolymorophism

Abstract Base Classes define generic interfaces and help us to create rather specific implementations.

•ABCs define only interfaces

•A class becomes an ABC if at least one of its functions is pure virtual function.

•No objects of ABCs can be instantiated!

•Only pointers of ABCs are defined. These pointers are used to select the functions from subclassess for run-time binding.

•Subclasses inherited from ABCs implement methods from the ABCs

Oo Programming/S. Kondakci 106

How Polymorophism Works

Polymorhism(PM)Polymorhism(PM) controls run-time behaviour of functions with the same name which are defined in the same class hierarchy

Polymorphism is realized via virtual functions (VF)virtual functions (VF).

Base class VF_func()

Sub class 2 VF_func()

Sub class N VF_func()

Sub class 1 VF_func()

VF_func() of one of The subclasses

Run- timeVF_func()

Oo Programming/S. Kondakci 107

Implementation of Implementation of PolimorphismPolimorphism

Polymorphism is implemented through virtual functions. When a request is made through a base class pointer, C++ chooses the correct overridden function in appropriate derived class associated with the object.

If a subclass derived from a BC (indeed abstract base class) with PVF and derived class has no definition for that PVF then the derived class is also an abstract class.

Oo Programming/S. Kondakci 108

How to Define Abstract How to Define Abstract ClassesClasses

A class is made abstract by declaring one or more of its virtual functions to be pure virtual function (PVF)pure virtual function (PVF).

A PVF is initialized to 0 when declared

class a {

private:

int a, b;

public:

virtual int add() const = 0;virtual int add() const = 0;

virtual void display() = 0;virtual void display() = 0;

}

Oo Programming/S. Kondakci 109

Use of non-virtual functionsIf a subclass derived from a BC with non-virtual functions then accessing derived class objects by use of base class pointers is nonsense. Because, the base class pointer even though pointing a subclass object will always point to its own object not to the derived class objects

class Base {

int a;

public:

Base () {a = 10;}

void display() {cout <<a<<endl;}

};

class Sub:public Base {

int b;

public:

Sub () {a = 20; Base();}

void display() {cout <<b<<endl;}

};

Oo Programming/S. Kondakci 110

Dynamic Binding: The run-time behaviour

int main() {

Base B, *Bptr = &B;

Sub S, *Sptr = &S;

Bptr->display(); // Call Base::display()

Sptr->display(); // Call Sub::display()

Bptr = &S;

Bptr->display(); // Call Base::display()

Bptr->Base::display(); // Explicit call to Base::display()

return 0;

}

Oo Programming/S. Kondakci 111

Example: Class Declarations I

#include <iostream>

using namespace std;

class Shape {

protected:

int width, height;

public:

Shape( int a=0, int b=0){

width = a;

height = b;

}

int area(){

cout << "Parent class area :" <<endl;

return 0;

}

};

Oo Programming/S. Kondakci 112

Example: Class Declarations II

class Rectangle: public Shape{

public:

Rectangle( int a=0, int b=0):Shape(a, b) { }

int area (){

cout << "Rectangle class area :" <<endl;

return (width * height);

}

};

class Triangle: public Shape{

public:

Triangle( int a=0, int b=0):Shape(a, b) { }

int area (){

cout << "Triangle class area :" <<endl;

return (width * height / 2);

}

};

Oo Programming/S. Kondakci 113

Example: main() part

int main( ) {

Shape *shape;

Rectangle rec(10,7);

Triangle tri(10,5);

// store the address of Rectangle

shape = &rec;

// call rectangle area.

shape->area();

// store the address of Triangle

shape = &tri;

// call triangle area.

shape->area();

return 0;

}

Output will be:

Parent class area

Parent class area

The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage - the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program.

Oo Programming/S. Kondakci 114

Example: With Virtual Functionclass Shape {

protected:

int width, height;

public:

Shape( int a=0, int b=0){

width = a;

height = b;

}

virtual int area(){ //Virtual func

cout << "Parent class area :" <<endl;

return 0;

}

};

This time, the compiler looks at the contents of the pointer instead of it's type. Hence, since addresses of objects of tri and rec classes are stored in *shape the respective area() function is called.

As you can see, each of the child classes has a separate implementation for the function area(). This is how polymorphism is generally used. You have different classes with a function of the same name, and even the same parameters, but with different implementations.

The output looks like:

Rectangle class area

Triangle class area

Virtual FunctionVirtual Function• A virtual function is a function in a base class that is

declared using the keyword virtual. Defining in a base class a virtual function, with other versions in derived classes, tells the compiler that we don't want static linkage for this function.

• With the virtual function we make the execution of the function to be at any given point in the program, which also can be based on the kind of object for which the funtion is called. This type of operation is referred to as dynamic linkage, or late binding, or run-time binding.

Pure Virtual FunctionPure Virtual Function

• It's possible that you would want to include a virtual function in a base class so that it may be redefined in a derived class to suit the objects of that class, but that there is no meaningful definition you could give for the function in the base class. Because, it only declares a virtual function and lets you to reshape it in your subclasses after your own taste and needs.

• A normal class containing at least one pure virtual function is called abstract class, which is only an interface and canot have objects created.

Pure Virtual Function

We can change the virtual function area() in the base class to the following:class Shape { protected: int width, height; public: Shape( int a=0, int b=0) { width = a; height = b; } // pure virtual function

virtual int area() = 0;};

The = 0 tells the compiler that the function has no body and above virtual function will be called pure virtual function.

Abstract Classes// abstract base class#include <iostream>using namespace std;

class Polygon { protected: int width, height; public: void set_values (int a, int b) { width=a; height=b; } virtual int area (void) =0;};

class Rectangle: public Polygon { public: int area (void) { return (width * height); }};

class Triangle: public Polygon { public: int area (void) { return (width * height / 2); }};

int main () {

Rectangle rect;

Triangle trgl;

Polygon * ppoly1 = &rect;

Polygon * ppoly2 = &trgl;

ppoly1->set_values (4,5);

ppoly2->set_values (4,5);

cout << ppoly1->area() << '\n';

cout << ppoly2->area() << '\n';

return 0;

}