Object-Oriented Programming

Size: px
Start display at page:

Download "Object-Oriented Programming"

Transcription

1 Object-Oriented Programming Section 3: Classes and inheritance (1) Piotr Mielecki, Ph. D.

2 Class vs. structure declaration Inheritance and access specifiers (private, protected, public) Friend methods Friend classes Overloading methods and operators (introduction)

3 Class vs. structure declaration C++ language is the result of evolution of classic C, extended by elements supporting OOP paradigm. Structural struct datatype in C++ can contain both data fields and functions (methods) as its members. The most significant difference between structure and class is using access specifiers (private, protected and public), which make encapsulation of particular members possible.

4 Example 1: Class vs. structure declaration (1) Declaration our header file: #ifndef CLASSES1_H_INCLUDED #define CLASSES1_H_INCLUDED struct Struct1 { int Var1; // Structures in C++ can contain methods. void setvar1(int i); int getvar1(); ; class Class1 { // All class members declared before first manifestly used access specifier // are private (encapsulated) by default. int Var1; // "public" access specifier makes all members of class // declared below accessible from outside. public: void setvar1(int i); int getvar1(); ; #endif // CLASSES1_H_INCLUDED

5 Example 1: Class vs. structure declaration (2) Implementation - our.cpp file: #include "Classes1.h" void Struct1::setVar1(int i) { Var1 = i; int Struct1::getVar1() { return Var1; void Class1::setVar1(int i) { Var1 = i; int Class1::getVar1() { return Var1;

6 Example 1: Class vs. structure declaration (3) Testing - our main.cpp file: #include <iostream> #include "Classes1.h" using namespace std; int main() { Struct1 mystructure; Class1 myclass; mystructure.setvar1(1); cout << "mystructure.var1 = " << mystructure.getvar1() << endl; mystructure.var1 = 2; // This assignment is legal. cout << "mystructure.var1 = " << mystructure.getvar1() << endl; myclass.setvar1(3); cout << "myclass.var1 = " << myclass.getvar1() << endl; // This is illegal: // myclass.var1 = 4; // Var1 is a private member of a Class1 class, so it's not directly // accessible from outside of object of this class type - encapsulation. // Structures don't support encapsulation. return 0;

7 Inheritance and access specifiers (1) General syntax for derived class declaration looks like this: class derived_class : access base1, access base2,... A derived class can directly access all the non-private (that means public and protected) members of its base class (or classes). When deriving a class from a base class, the base class may be inherited through public, protected or private inheritance. Constructors, destructors and assign operator (=) are not inherited from base class to derived class. If we want to use the base class constructor implementing derived class constructor it can be invoked in initializer list, like in this example (see also Example 3 in Section 2): NewClass::NewClass( int xx, int yy, int zz ) : BaseClass( xx, yy ), zz { z = zz;

8 Inheritance and access specifiers (2) When deriving a class from a public base class, public members of the base class become public members of the derived class and protected members of the base class become protected members of the derived class. A private members of base class are never accessible directly from a derived class, but can be accessed through calls to the public and protected members of the base class. When deriving from a protected base class, public and protected members of the base class become protected members of the derived class. When deriving from a private base class, public and protected members of the base class become private members of the derived class.

9 Example 2: Inheritance and access specifiers (1) Declaration our header file (1): #ifndef CLASSES2_H_INCLUDED #define CLASSES2_H_INCLUDED // Problems with constant PI value can occur depending on compiler. #ifndef M_PIl # define M_PIl L #endif // M_PIl // Base class - Point: class Point { // To give the derived class direct access to attributes // we are using "protected" access specifier. protected: double x, y; public: // Constructor with default values: Point(double newx = 0, double newy = 0); ; void setx(double newx); // Setter for x double getx() const; // Getter for x void sety(double newy); // Setter for y double gety() const; // Getter for y void setposition(double newx, double newy);

10 Example 2: Inheritance and access specifiers (2) Declaration our header file (2): // Derived class - Circle: class Circle : public Point { // Maybe someone wants to derive a Cylinder class? protected: double r; public: // Constructor will be not inherited from base class. Circle(double newx = 0, double newy = 0, double newr = 1); void setr(double newr); double getr() const; // Setter for r // Getter for r ; double getarea() const; // A public method which returns area. double getperimeter()const; // A public method which returns perimeter.

11 Example 2: Inheritance and access specifiers (3) Declaration our header file (3): // Derived class - Rectangle: class Rectangle : public Point { // Maybe someone wants to derive a Cuboid class? protected: double a, b; public: // Constructor will be not inherited from base class. Rectangle(double newx = 0, double newy = 0, double newa = 1, double newb = 1); void seta(double newa); double geta() const; void setb(double newa); double getb() const; // Setter for a // Getter for a // Setter for b // Getter for b ; double getarea() const; // A public method which returns area. double getperimeter() const; // A public method which returns perimeter. double getdiagonal() const; // A public method which returns diagonal. #endif // CLASSES2_H_INCLUDED

12 Example 2: Inheritance and access specifiers (4) Implementation our.cpp file (1): #include "Classes2.h" #include <math.h> Point::Point(double newx, double newy) { x = newx; y = newy; void Point::setX(double newx) { x = newx; double Point::getX(void) const { return x; void Point::setY(double newy) { y = newy; double Point::getY(void) const { return y; void Point::setPosition(double newx, double newy) { x = newx; y = newy;

13 Example 2: Inheritance and access specifiers (4) Implementation our.cpp file (2): Circle::Circle(double newx, double newy, double newr) { x = newx; y = newy; setr(newr); // Constructor can call class methods without prefix. void Circle::setR(double newr) { r = newr >= 0? newr : -1 * newr; double Circle::getR() const { return r; double Circle::getArea() const { return M_PIl * r * r; double Circle::getPerimeter() const { return 2 * M_PIl * r;

14 Example 2: Inheritance and access specifiers (5) Implementation our.cpp file (3): Rectangle::Rectangle(double newx, double newy, double newa, double newb) { x = newx; y = newy; seta(newa); setb(newb); void Rectangle::setA(double newa) { a = newa >= 0? newa : -1 * newa; double Rectangle::getA() const { return a; void Rectangle::setB(double newb) { b = newb >= 0? newb : -1 * newb; double Rectangle::getB() const { return b;

15 Example 2: Inheritance and access specifiers (6) Implementation our.cpp file (4): double Rectangle::getArea() const { return a * b; double Rectangle::getPerimeter() const { return 2 * a + 2 * b; double Rectangle::getDiagonal() const { return sqrt(a * a + b * b);

16 Example 2: Inheritance and access specifiers (7) Testing - our main.cpp file (1): #include <iostream> #include "Classes2.h" using namespace std; int main() { Circle mycircle1; Circle mycircle2(10, 10, 10); Rectangle myrectangle(30, 30, 10, 20); cout << "mycircle1: " << endl; cout << "x = " << mycircle1.getx(); cout << ", y = " << mycircle1.gety(); cout << ", r = " << mycircle1.getr(); cout << ", Area = " << mycircle1.getarea(); cout << ", Perimeter = " << mycircle1.getperimeter() << endl; cout << "mycircle2: " << endl; cout << "x = " << mycircle2.getx(); cout << ", y = " << mycircle2.gety(); cout << ", r = " << mycircle2.getr(); cout << ", Area = " << mycircle2.getarea(); cout << ", Perimeter = " << mycircle2.getperimeter() << endl;

17 Example 2: Inheritance and access specifiers (8) Testing - our main.cpp file (2): cout << "myrectangle:" << endl; cout << "x = " << myrectangle.getx(); cout << ", y = " << myrectangle.gety(); cout << ", a = " << myrectangle.geta(); cout << ", b = " << myrectangle.getb(); cout << ", Area = " << myrectangle.getarea(); cout << ", Perimeter = " << myrectangle.getperimeter(); cout << ", Diagonal = " << myrectangle.getdiagonal() << endl; return 0;

18 Friend methods When declaring a class its author can give a direct access to all its members (public, protected and private) for functions (methods) form outside of the class. Prototypes for those methods are declared inside the class declaration and prefixed with friend keyword. Friend function can be implemented in any other module of program, by other member of developers team for example. In fact we can say that friend function is kind of backdoor to the class overcomes the access specifiers. That s why the key (friend method declaration inside the class) is kept by author of the class.

19 Example 3: Friend functions (1) Declaration our Point.h header file for Point class (1): #ifndef POINT_H_INCLUDED #define POINT_H_INCLUDED // Those 2 declarations are "promising" classes used by friend // functions but not declared in this file. class Circle; // Forward declaration of Circle class class Rectangle; // Forward declaration of Rectangle class // Base class - Point: class Point { // To give the derived class direct access to attributes // we are using "protected" access specifier. protected: double x, y; public: // Constructor with default values: Point(double newx = 0, double newy = 0); void setx(double newx); // Setter for x double getx() const; // Getter for x void sety(double newy); // Setter for y double gety() const; // Getter for y void setposition(double newx, double newy);

20 Example 3: Friend functions (2) Declaration our Point.h header file for Point class (2): // Compiler knows about Circle and Rectangle classes // because of forward declarations. // So we can declare two overloaded functions which are // detecting if point is inside the circle or rectangle // this way: friend bool pointinshape(point pnt, Circle circ); friend bool pointinshape(point pnt, Rectangle rect);; // We can add functions for console interface also as "friend" ones: friend std::ostream &operator << (std::ostream &os, Point &pnt); friend std::istream &operator >> (std::istream &is, Point &pnt); #endif // POINT_H_INCLUDED

21 Declaration our Circle.h header file for Circle class (1): #ifndef CIRCLE_H_INCLUDED #define CIRCLE_H_INCLUDED #include "Point.h" Example 3: Friend functions (3) // Problems with constant PI value can occur depending on compiler. #ifndef M_PIl # define M_PIl L #endif // M_PIl // Class derived form Point - Circle: class Circle : public Point { // Maybe someone wants to derive a Cylinder class? protected: double r; public: // Constructor will be not inherited from base class. Circle(double newx = 0, double newy = 0, double newr = 1); void setr(double newr); double getr() const; // Setter for r // Getter for r

22 Example 3: Friend functions (4) Declaration our Circle.h header file for Circle class (2): double getarea() const; // A public method which returns area. double getperimeter()const; // A public method which returns perimeter. friend bool pointinshape(point pnt, Circle circ); ; friend std::ostream &operator << (std::ostream &os, Circle &circ); friend std::istream &operator >> (std::istream &is, Circle &circ); #endif // CIRCLE_H_INCLUDED

23 Declaration our Rectangle.h header file for Rectangle class (1): #ifndef RECTANGLE_H_INCLUDED #define RECTANGLE_H_INCLUDED #include "Point.h" Example 3: Friend functions (5) // Class derived from Point - Rectangle: class Rectangle : public Point { // Maybe someone wants to derive a Cuboid class? protected: double a, b; public: // Constructor will be not inherited from base class. Rectangle(double newx = 0, double newy = 0, double newa = 1, double newb = 1); void seta(double newa); double geta() const; void setb(double newa); double getb() const; // Setter for a // Getter for a // Setter for b // Getter for b

24 Example 3: Friend functions (6) Declaration our Rectangle.h header file for Rectangle class (2): double getarea() const; double getperimeter() const; double getdiagonal() const; // A public method which returns area. // A public method which returns perimeter. // A public method which returns diagonal. friend bool pointinshape(point pnt, Rectangle rect); ; friend std::ostream &operator << (std::ostream &os, Rectangle &rect); friend std::istream &operator >> (std::istream &is, Rectangle &rect); #endif // RECTANGLE_H_INCLUDED

25 Implementation our Point.cpp file for Point class: #include "Point.h" Example 3: Friend functions (7) Point::Point(double newx, double newy) { x = newx; y = newy; void Point::setX(double newx) { x = newx; double Point::getX() const { return x; void Point::setY(double newy) { y = newy; double Point::getY() const { return y; void Point::setPosition(double newx, double newy) { x = newx; y = newy;

26 Example 3: Friend functions (8) Implementation our Circle.cpp file for Circle class: #define _USE_MATH_DEFINES #include <math.h> #include "Circle.h" Circle::Circle(double newx, double newy, double newr) { x = newx; y = newy; setr( newr ); void Circle::setR(double newr) { r = newr >= 0? newr : -1 * newr; double Circle::getR() const { return r; double Circle::getArea() const { return M_PIl * r * r; double Circle::getPerimeter() const { return 2 * M_PIl * r;

27 Example 3: Friend functions (9) Implementation our Rectangle.cpp file for Rectangle class (1): #include <math.h> #include "Rectangle.h" Rectangle::Rectangle(double newx, double newy, double newa, double newb) { x = newx; y = newy; seta(newa); setb(newb); void Rectangle::setA(double newa) { a = newa >= 0? newa : -1 * newa; double Rectangle::getA() const { return a; void Rectangle::setB(double newb) { b = newb >= 0? newb : -1 * newb; double Rectangle::getB() const { return b;

28 Example 3: Friend functions (10) Implementation our Rectangle.cpp file for Rectangle class (2): double Rectangle::getArea() const { return a * b; double Rectangle::getPerimeter() const { return 2 * a + 2 * b; double Rectangle::getDiagonal() const { return sqrt( a * a + b * b );

29 Example 3: Friend functions (11) Implementation our Friends.cpp file for friend functions (1): // Overloaded functions for detecting if given point is inside the object. // For Circle class: bool pointinshape(point pnt, Circle circ) { if( (pnt.x - circ.x)*(pnt.x - circ.x) + (pnt.y - circ.y)*(pnt.y - circ.y) \ <= circ.r * circ.r ) return true; else return false; // For Rectangle class: bool pointinshape(point pnt, Rectangle rect) { if( (pnt.x >= rect.x) && (pnt.x <= rect.x + rect.a) && \ (pnt.y >= rect.y) && (pnt.y <= rect.y + rect.b) ) return true; else return false;

30 Example 3: Friend functions (12) Implementation our Friends.cpp file for friend functions (2): // Functions supporting console interface ("views") by overloading // the << and >> operators. // For Point class: std::ostream &operator << (std::ostream &os, Point &pnt) { return std::cout << "x = " << pnt.x << ", y = " << pnt.y; std::istream &operator >> (std::istream &is, Point &pnt) { return std::cin >> pnt.x >> pnt.y; // For Circle class: std::ostream &operator << (std::ostream &os, Circle &circ) { return std::cout << "x = " << circ.x << ", y = " << circ.y << \ ", r = " << circ.r; std::istream &operator >> (std::istream &is, Circle &circ) { return std::cin >> circ.x >> circ.y >> circ.r; // For Rectangle class: std::ostream &operator << (std::ostream &os, Rectangle &rect) { return std::cout << "x = " << rect.x << ", y = " << rect.y << \ ", a = " << rect.a << ", b = " << rect.b; std::istream &operator >> (std::istream &is, Rectangle &rect) { return std::cin >> rect.x >> rect.y >> rect.a >> rect.b;

31 Example 3: Friend functions (13) Testing our main.cpp file for main segment (1): #include <iostream> #include "Point.h" #include "Circle.h" #include "Rectangle.h" using namespace std; int main() { Point mypoint; Circle mycircle; Rectangle myrectangle; string choice;

32 Example 3: Friend functions (14) Testing our main.cpp file for main segment (2): // Program control loop: do { // We are using user interface ("view") on standard text console // implemented as appropriate friend functions, which are overloading // << and >> operators of C++ iostream for Point, Circle and Rectangle // classes. cout << "mypoint: enter x and y (separated with space): "; cin >> mypoint; cout << "mypoint: " << mypoint << endl; cout << "mycircle: enter x, y and r (separated with spaces): "; cin >> mycircle; cout << "mycircle: " << mycircle << endl; cout << "myrectangle: enter x, y, a and b (separated with spaces): "; cin >> myrectangle; cout << "myrectangle: " << myrectangle << endl;

33 Example 3: Friend functions (15) Testing our main.cpp file for main segment (3): // This time object attributes are read by getters (this still works, of course): cout << endl << "Objects:" << endl; cout << "mypoint: x = " << mypoint.getx() << ", y = " << mypoint.gety() << endl; cout << "mycircle: x = " << mycircle.getx() << ", y = " << mycircle.gety(); cout << ", r = " << mycircle.getr() << endl; cout << "myrectangle: x = " << myrectangle.getx() << ", y = " \ << myrectangle.gety(); cout << ", a = " << myrectangle.geta() << ", b = " << myrectangle.getb() << endl; if( pointinshape(mypoint, mycircle) ) cout << "mypoint is inside the mycircle." << endl; else cout << "mypoint is outside the mycircle." << endl; if( pointinshape(mypoint, myrectangle) ) cout << "mypoint is inside the myrectangle." << endl; else cout << "mypoint is outside the myrectangle." << endl; cout << endl << "Do you want to set new values (Y/N)? "; cin >> choice; while( choice == "Y" choice == "y" ); return 0;

34 Example 3: Friend functions (16) Testing screenshot: Picture above shows results from running program.

35 Example 3: Friend functions (summary) In this example functions declared as friend ones have direct access to all attributes and methods of classes, although this access is granted in declarations of classes. Friend functions are not the members of classes, they can only work with objects of those classes from outside. Implementing the access (user interface) in friend functions (overloading of << and >> operators in this example) separates this interface from classes themselves. Author of the class only specifies way in which particular kind of user interface (standard text console in this case, but something like this can be specified for Windows controls, HTML tags etc.) can interact with object of this class. In well organized project we should clearly separate the user interface (collection of views Windows or X Window forms, HTML pages etc.) and code of application itself (data model, algorithms, communication interface etc.).

36 Friend classes Instead of giving direct access to all members of the class for particular functions, author can declare the friend class. Friend class (or classes) can also be implemented in any other module of program, by other member of developers team for example (it s a matter of trust). Author of the classes which accept friend class declares only the name of this friend class doesn t need to declare prototypes for particular functions / methods. The modifications in code from Example 3 are shown in next example. This time project is clearly arranged data model (Point, Circle and Rectangle classes), supported with some extra processing in DataFriends class is separated from user interface (view) supported by ViewFriends class. In this example ViewFriends class supports text console interface. In other project it can support controls available in Windows GUI, HTML etc. Only this class (and main segment) will be implemented in different way then.

37 Declaration our header file for Point class (1): #ifndef POINT_H_INCLUDED #define POINT_H_INCLUDED Example 4: Friend classes (1) // Forward declarations of friend or derived classes are not necessary. // Base class - Point: class Point { // To give the derived class direct access to attributes // we are using "protected" access specifier. protected: double x, y; public: // Constructor with default values: Point(double newx = 0, double newy = 0); void setx(double newx); // Setter for x double getx() const; // Getter for x void sety(double newy); // Setter for y double gety() const; // Getter for y void setposition(double newx, double newy);

38 Example 4: Friend classes (2) Declaration our header file for Point class (2): ; friend class DataFriends; friend class ViewFriends; #endif // POINT_H_INCLUDED

39 Declaration our header file for Circle class (1): #ifndef CIRCLE_H_INCLUDED #define CIRCLE_H_INCLUDED #include "Point.h" Example 4: Friend classes (3) // Problems with constant PI value can occur depending on compiler. #ifndef M_PIl # define M_PIl L #endif // M_PIl // Class derived form Point - Circle: class Circle : public Point { // Maybe someone wants to derive a Cylinder class? protected: double r; public: // Constructor will be not inherited from base class. Circle(double newx = 0, double newy = 0, double newr = 1); void setr(double newr); double getr() const; // Setter for r // Getter for r

40 Example 4: Friend classes (4) Declaration our header file for Circle class (2): double getarea() const; // A public method which returns area. double getperimeter()const; // A public method which returns perimeter. ; friend class DataFriends; friend class ViewFriends; #endif // CIRCLE_H_INCLUDED

41 Declaration our header file for Rectangle class (1): #ifndef RECTANGLE_H_INCLUDED #define RECTANGLE_H_INCLUDED #include "Point.h" Example 4: Friend classes (5) // Class derived from Point - Rectangle: class Rectangle : public Point { // Maybe someone wants to derive a Cuboid class? protected: double a, b; public: // Constructor will be not inherited from base class. Rectangle(double newx = 0, double newy = 0, double newa = 1, double newb = 1); void seta(double newa); double geta() const; void setb(double newb); double getb() const; // Setter for a // Getter for a // Setter for b // Getter for b

42 Example 4: Friend classes (6) Declaration our header file for Rectangle class (2): double getarea() const; double getperimeter() const; double getdiagonal() const; // A public method which returns area. // A public method which returns perimeter. // A public method which returns diagonal. ; friend class DataFriends; friend class ViewFriends; #endif // RECTANGLE_H_INCLUDED

43 Declaration our header file for DataFriends class (1): #ifndef DATAFRIENDS_H_INCLUDED #define DATAFRIENDS_H_INCLUDED #include "Point.h" #include "Circle.h" #include "Rectangle.h" Example 4: Friend classes (7) class DataFriends { public: // Overloaded methods for detecting if given point is inside the shape. // For Circle: bool pointinshape(point pnt, Circle circ); // For Rectangle: bool pointinshape(point pnt, Rectangle rect);

44 Example 4: Friend classes (8) Declaration our header file for DataFriends class (2): // Methods for quick setting attributes of shapes (maybe someone needs them). // Object must be passed to function by pointer - then function works // on object itself, not on its copy. // In this case methods are not overloaded as setshape() for example, // but of course we can do it. ; // Method which sets all attributes of the Circle class object. void setcircle(circle *cr, double newx, double newy, double newr); // Method which sets all attributes of the Rectangle class object. void setrectangle(rectangle *rt, double newx, double newy, double newa, double newb); #endif // DATAFRIENDS_H_INCLUDED

45 Example 4: Friend classes (9) Declaration our header file for ViewFriends class: #ifndef VIEWFRIENDS_H_INCLUDED #define VIEWFRIENDS_H_INCLUDED #include "Point.h" #include "Circle.h" #include "Rectangle.h" class ViewFriends { public: // Overloaded methods supporting console interface ("views"). // For Point class: void viewinput(point *pnt); void viewoutput(point pnt); void viewfullinfo(point pnt); // For Circle class: void viewinput(circle *circ); void viewoutput(circle circ); void viewfullinfo(circle circ); // For Rectangle class: void viewinput(rectangle *rect); void viewoutput(rectangle rect); void viewfullinfo(rectangle rect); ; #endif // VIEWFRIENDS_H_INCLUDED

46 Implementation our.cpp file for Point class: #include "Point.h" Example 4: Friend classes (10) Point::Point(double newx, double newy) { x = newx; y = newy; void Point::setX(double newx) { x = newx; double Point::getX() const { return x; void Point::setY(double newy) { y = newy; double Point::getY() const { return y; void Point::setPosition(double newx, double newy) { x = newx; y = newy;

47 Implementation our.cpp file for Circle class: #include <math.h> #include "Circle.h" Example 4: Friend classes (11) Circle::Circle(double newx, double newy, double newr) { x = newx; y = newy; setr(newr); void Circle::setR(double newr) { r = newr >= 0? newr : -1 * newr; double Circle::getR() const { return r; double Circle::getArea() const { return M_PIl * r * r; double Circle::getPerimeter() const { return 2 * M_PIl * r;

48 Implementation our.cpp file for Rectangle class (1): #include <math.h> #include "Rectangle.h" Example 4: Friend classes (12) Rectangle::Rectangle(double newx, double newy, double newa, double newb) { x = newx; y = newy; seta(newa); setb(newb); void Rectangle::setA(double newa) { a = newa >= 0? newa : -1 * newa; double Rectangle::getA() const { return a; void Rectangle::setB(double newb) { b = newb >= 0? newb : -1 * newb; double Rectangle::getB() const { return b;

49 Example 4: Friend classes (13) Implementation our.cpp file for Rectangle class (2): double Rectangle::getArea() const { return a * b; double Rectangle::getPerimeter() const { return 2 * a + 2 * b; double Rectangle::getDiagonal() const { return sqrt(a * a + b * b);

50 Implementation our.cpp file for DataFriends class (1): #include "DataFriends.h" Example 4: Friend classes (14) bool DataFriends::pointInShape(Point pnt, Circle circ) { if( (pnt.x - circ.x)*(pnt.x - circ.x) + (pnt.y - circ.y)*(pnt.y - circ.y)\ <= circ.r * circ.r ) return true; else return false; bool DataFriends::pointInShape(Point pnt, Rectangle rect) { if( (pnt.x >= rect.x)&&(pnt.x <= rect.x + rect.a) \ &&(pnt.y >= rect.y)&&(pnt.y <= rect.y + rect.b) ) return true; else return false;

51 Example 4: Friend classes (15) Implementation our.cpp file for DataFriends class (2): void DataFriends::setCircle(Circle *cr, double newx, double newy, double newr) { cr->x = newx; cr->y = newy; cr->r = newr; void DataFriends::setRectangle(Rectangle *rt, double newx, double newy, double newa, double newb) { rt->x = newx; rt->y = newy; rt->a = newa; rt->b = newb;

52 Example 4: Friend classes (16) Implementation our.cpp file for ViewFriends class (1): #include <iostream> #include "ViewFriends.h" void ViewFriends::viewInput(Point *pnt) { std::cin >> pnt->x >> pnt->y; void ViewFriends::viewOutput(Point pnt) { std::cout << "Point: x = " << pnt.x << ", y = " << pnt.y << std::endl; void ViewFriends::viewFullInfo(Point pnt) { std::cout << "Point: x = " << pnt.x << ", y = " << pnt.y << std::endl; void ViewFriends::viewInput(Circle *circ) { std::cin >> circ->x >> circ->y >> circ->r; void ViewFriends::viewOutput(Circle circ) { std::cout << "Circle: x = " << circ.x << ", y = " << circ.y << ", r = " \ << circ.r << std::endl; void ViewFriends::viewFullInfo(Circle circ) { std::cout << "Circle: x = " << circ.x << ", y = " << circ.y << ", r = " \ << circ.r << std::endl; std::cout << " area = " << circ.getarea() << ", perimeter = " \ << circ.getperimeter() << std::endl;

53 Example 4: Friend classes (17) Implementation our.cpp file for ViewFriends class (2): void ViewFriends::viewInput(Rectangle *rect) { std::cin >> rect->x >> rect->y >> rect->a >> rect->b; void ViewFriends::viewOutput(Rectangle rect) { std::cout << "Rectangle: x = " << rect.x << ", y = " << rect.y << ", a = " \ << rect.a << ", b = " << rect.b << std::endl; void ViewFriends::viewFullInfo(Rectangle rect) { std::cout << "Rectangle: x = " << rect.x << ", y = " << rect.y << ", a = " \ << rect.a << ", b = " << rect.b << std::endl; std::cout << " area = " << rect.getarea() << ", perimeter = " \ << rect.getperimeter() << rect.getperimeter() << ", diagonal = " \ << rect.getdiagonal() << std::endl;

54 Testing our.cpp file for main segment (1): #include <iostream> #include "Point.h" #include "Circle.h" #include "Rectangle.h" #include "DataFriends.h" #include "ViewFriends.h" using namespace std; Example 4: Friend classes (18) int main() { Point mypoint; Circle mycircle; Rectangle myrectangle; DataFriends mydatafriends; ViewFriends myviewfriends; string choice;

55 Example 4: Friend classes (19) Testing our.cpp file for main segment (2): // Program control loop: do { cout << "mypoint: enter x and y (separated with space): "; myviewfriends.viewinput(&mypoint); myviewfriends.viewoutput(mypoint); cout << "mycircle: enter x, y and r (separated with spaces): "; myviewfriends.viewinput(&mycircle); myviewfriends.viewoutput(mycircle); cout << "myrectangle: enter x, y, a and b (separated with spaces): "; myviewfriends.viewinput(&myrectangle); myviewfriends.viewoutput(myrectangle);

56 Example 4: Friend classes (20) Testing our.cpp file for main segment (3): cout << endl << "Objects:" << endl; myviewfriends.viewfullinfo(mypoint); myviewfriends.viewfullinfo(mycircle); myviewfriends.viewfullinfo(myrectangle); if( mydatafriends.pointinshape(mypoint, mycircle) ) cout << "mypoint is inside the mycircle." << endl; else cout << "mypoint is outside the mycircle." << endl; if( mydatafriends.pointinshape(mypoint, myrectangle) ) cout << "mypoint is inside the myrectangle." << endl; else cout << "mypoint is outside the myrectangle." << endl; cout << endl << "Do you want to set new values (Y/N)? "; cin >> choice; while( choice == "Y" choice == "y" ); return 0;

57 Example 4: Friend classes (summary) Solution shown in this example is more elegant than this from Example 3. First of all main segment can be implemented as user interface only (organizing views) in fact we don t need to use here methods other than supported by ViewFriends class, designed exactly for this purpose. Class DataFriends helps us to perform some processing with data (acquired by user interface, for example), but it doesn t depend on this interface (will be the same for GUI applications, for other system platforms etc.). The same is true about all methods available for Point, Circle and Rectangle classes we don t need to modify them in other projects. Friend classes are very powerful as technique for implementing this kind of interface, but they have one important disadvantage they are by-passing the security means given by encapsulation (private access to some attributes and methods). So we should use this technique very carefully.

58 Overloading methods and operators (introduction) In last two examples (3 and 4) overloading of some methods (and operator functions) was introduced in advance. It will be explained deeper in Section 4. Overloading helps to create code more transparent than using numerous methods with different names, although compiler still has to generate different versions of functions and insert them to executable code not all of them will be used. More optimal and efficient code (limited to methods used in particular context) is generated when we are using techniques like virtual inheritance and polymorphism or templates (will be explained in next sections). Overloading of operators gives the same benefits and issues, as overloading of normal methods. Next example (Example 5) shows implementation of basic operations on 2-dimensional vectors (useful for solving mechanical problems, for example). Operators like ==,!=, =, and + are overloaded.

59 Data model definition of the Vector2D class in header file (1): #ifndef VECTOR2D_H_INCLUDED #define VECTOR2D_H_INCLUDED Example 5: Class with overloaded operators Vector2D (1) #include "Point.h" // Base Point class (nearly the same as in previous examples) #include <math.h> // Problems with constant PI value can occur depending on compiler. #ifndef M_PIl # define M_PIl L #endif // M_PIl // Class derived form Point - Vector2D: class Vector2D : public Point { protected: double l; // Length of vector (module) [mm] double alpha; // Angle to X-axis [deg] public: // Constructor will be not inherited from base class. Vector2D(double newx = 0, double newy = 0, double newl = 0, double newa = 0); void setlength(double newl); double getlength() const; void setangle(double newa); double getangle() const; // Setter for l // Getter for l // Setter for alpha (input in [deg]) // Getter for alpha (return in [deg])

60 Example 5: Class with overloaded operators Vector2D (2) Data model definition of the Vector2D class in header file (2): double getcompx() const; double getcompy() const; // A public method which returns component X // A public method which returns component Y // Four overloaded operators: equal, not equal, assignment and addition: bool operator ==(const Vector2D v2); bool operator!=(const Vector2D v2); void operator =(const Vector2D v2); Vector2D operator +(const Vector2D v2); ; // Friend class supporting views for text console: friend class ViewFriends; #endif // VECTOR2D_H_INCLUDED

61 Data model definition of the base Point class in header file: #ifndef POINT_H_INCLUDED #define POINT_H_INCLUDED Example 5: Class with overloaded operators Vector2D (3) // Base class - Point: class Point { // To give the derived class direct access to attributes // we are using "protected" access specifier. protected: double x, y; public: // Constructor with default values: Point(double newx = 0, double newy = 0); void setx(double newx); // Setter for x double getx() const; // Getter for x void sety(double newy); // Setter for y double gety() const; // Getter for y void setposition(double newx, double newy); ; friend class ViewFriends; // In this case we need only one friend class. #endif // POINT_H_INCLUDED

62 Data model implementation of the base Point class in.cpp file: #include "Point.h" Example 5: Class with overloaded operators Vector2D (4) Point::Point(double newx, double newy) { x = newx; y = newy; void Point::setX(double newx) { x = newx; double Point::getX() const { return x; void Point::setY(double newy) { y = newy; double Point::getY() const { return y; void Point::setPosition(double newx, double newy) { x = newx; y = newy;

63 Data model implementation of the Vector2D class in.cpp file (1): #include <math.h> #include "Vector2D.h" Example 5: Class with overloaded operators Vector2D (5) Vector2D::Vector2D(double newx, double newy, double newl, double newa) { x = newx; y = newy; setlength(newl); setangle(newa); void Vector2D::setLength(double newl) { l = newl >= 0? newl : -1 * newl; double Vector2D::getLength() const { return l; void Vector2D::setAngle(double newa) { while( sqrt(newa * newa) >= 360 ){ newa = newa > 0? newa : newa + 360; alpha = newa; double Vector2D::getAngle() const { return alpha;

64 Example 5: Class with overloaded operators Vector2D (6) Data model implementation of the Vector2D class in.cpp file (2): double Vector2D::getCompX() const { return l * cos(alpha * M_PIl / 180); double Vector2D::getCompY() const { return l * sin(alpha * M_PIl / 180); bool Vector2D::operator ==(const Vector2D v2) { if( x == v2.x && y == v2.y && l == v2.l && alpha == v2.alpha ) return true; else return false; bool Vector2D::operator!=(const Vector2D v2) { if( x!= v2.x y!= v2.y l!= v2.l alpha!= v2.alpha ) return true; else return false;

65 Example 5: Class with overloaded operators Vector2D (7) Data model implementation of the Vector2D class in.cpp file (3): void Vector2D::operator =(const Vector2D v2) { // Pointer "this" is not necessary //this->x = v2.x; //this->y = v2.y; //this->l = v2.l; //this->alpha = v2.alpha; x = v2.x; y = v2.y; l = v2.l; alpha = v2.alpha;

66 Example 5: Class with overloaded operators Vector2D (8) Data model implementation of the Vector2D class in.cpp file (4): Vector2D Vector2D::operator +(const Vector2D v2) { double dx, dy, dl, beta; if( x!= v2.x y!= v2.y ) // Vectors have different points of application, // so we can't add them - return first one. return Vector2D(x, y, l, alpha); else { dx = getcompx() + v2.getcompx(); dy = getcompy() + v2.getcompy(); dl = sqrt(dx * dx + dy * dy); beta = atan(dy / dx); return Vector2D(x, y, dl, beta * 180 / M_PIl);

67 Views definition of the ViewFriends class in header file: #ifndef VIEWFRIENDS_H_INCLUDED #define VIEWFRIENDS_H_INCLUDED #include "Point.h" #include "Vector2D.h" Example 5: Class with overloaded operators Vector2D (9) class ViewFriends { public: // Overloaded methods supporting console interface ("views"). // For Point class: void viewinput(point *pnt); void viewoutput(point pnt); void viewfullinfo(point pnt); // For Vector2D class: void viewinput(vector2d *vct); void viewoutput(vector2d vct); void viewfullinfo(vector2d vct); ; #endif // VIEWFRIENDS_H_INCLUDED

68 Views implementation of the ViewFriends class in.cpp file (1): #include <iostream> #include "ViewFriends.h" Example 5: Class with overloaded operators Vector2D (10) void ViewFriends::viewInput(Point *pnt) { std::cin >> pnt->x >> pnt->y; void ViewFriends::viewOutput(Point pnt) { std::cout << "Point: x = " << pnt.x << ", y = " << pnt.y << std::endl; void ViewFriends::viewFullInfo(Point pnt) { std::cout << "Point: x = " << pnt.x << ", y = " << pnt.y << std::endl; void ViewFriends::viewInput(Vector2D *vct) { double newl, newa; std::cin >> vct->x >> vct->y >> newl >> newa; vct->setlength(newl); vct->setangle(newa); void ViewFriends::viewOutput(Vector2D vct) { std::cout << "Vector2D: x = " << vct.x << ", y = " << vct.y \ << ", length = " << vct.l << ", angle = " << vct.alpha << std::endl;

69 Example 5: Class with overloaded operators Vector2D (11) Views implementation of the ViewFriends class in.cpp file (2): void ViewFriends::viewFullInfo(Vector2D vct) { std::cout << "Vector2D: x = " << vct.x << ", y = " << vct.y \ << ", length = " << vct.l << ", angle = " << vct.alpha << std::endl; std::cout << " comp. X = " << vct.getcompx() \ << ", comp. Y = " << vct.getcompy() << std::endl;

70 Testing our main.cpp file (1): #include <iostream> #include "Vector2D.h" #include "ViewFriends.h" using namespace std; Example 5: Class with overloaded operators Vector2D (12) int main() { Vector2D myvectors[4]; ViewFriends myviewfriends; int i, j; string choice; // Program control loop: do { cout << "myvectors[0]: enter x, y, length and angle (separated with spaces): "; myviewfriends.viewinput(&myvectors[0]); myviewfriends.viewoutput(myvectors[0]); cout << "myvectors[1]: enter x, y, length and angle (separated with spaces): "; myviewfriends.viewinput(&myvectors[1]); myviewfriends.viewoutput(myvectors[1]);

71 Example 5: Class with overloaded operators Vector2D (13) Testing our main.cpp file (2): myvectors[2] = myvectors[0]; myvectors[3] = myvectors[0] + myvectors[1]; for( i = 0; i < 4; i++ ) { cout << endl << "myvectors[" << i << "]" << endl; myviewfriends.viewfullinfo(myvectors[i]); cout << endl; for( i = 0; i < 4; i++ ) { for( j = i+1; j < 4; j++ ) { if( myvectors[i] == myvectors[j] ) cout << "myvectors[" << i << "] == myvectors[" << j << "]" << endl; cout << endl << "Do you want to set new values (Y/N)? "; cin >> choice; while( choice == "Y" choice == "y" ); return 0;

72 Example 5: Class with overloaded operators Vector2D (14) Testing screenshot: Picture above shows results from running program. Please consider limited accuracy of calculations (myvectors[1]). Double float (64-bit) numbers were used, but some error of approximation exists (about for this particular value).

Ch 2 ADTs and C++ Classes

Ch 2 ADTs and C++ Classes Ch 2 ADTs and C++ Classes Object Oriented Programming & Design Constructing Objects Hiding the Implementation Objects as Arguments and Return Values Operator Overloading 1 Object-Oriented Programming &

More information

CS11 Intro C++ Spring 2018 Lecture 3

CS11 Intro C++ Spring 2018 Lecture 3 CS11 Intro C++ Spring 2018 Lecture 3 C++ File I/O We have already seen C++ stream I/O #include cout > name; cout

More information

CS11 Introduction to C++ Fall Lecture 1

CS11 Introduction to C++ Fall Lecture 1 CS11 Introduction to C++ Fall 2006-2007 Lecture 1 Welcome! 8 Lectures (~1 hour) Slides posted on CS11 website http://www.cs.caltech.edu/courses/cs11 7 Lab Assignments on course website Available on Monday

More information

CS11 Intro C++ Spring 2018 Lecture 1

CS11 Intro C++ Spring 2018 Lecture 1 CS11 Intro C++ Spring 2018 Lecture 1 Welcome to CS11 Intro C++! An introduction to the C++ programming language and tools Prerequisites: CS11 C track, or equivalent experience with a curly-brace language,

More information

Inheritance, and Polymorphism.

Inheritance, and Polymorphism. Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to

More information

Introduction to Classes

Introduction to Classes Introduction to Classes Procedural and Object-Oriented Programming Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a program Object-Oriented

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology Lecture 8: Object-Oriented Programming (OOP) 1 Introduction to C++ 2 Overview Additional features compared to C: Object-oriented programming (OOP) Generic programming (template) Many other small changes

More information

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay

Classes - 2. Data Processing Course, I. Hrivnacova, IPN Orsay Classes - 2 Data Processing Course, I. Hrivnacova, IPN Orsay OOP, Classes Reminder Requirements for a Class Class Development Constructor Access Control Modifiers Getters, Setters Keyword this const Member

More information

Namespaces and Class Hierarchies

Namespaces and Class Hierarchies and 1 2 3 MCS 360 Lecture 9 Introduction to Data Structures Jan Verschelde, 13 September 2010 and 1 2 3 Suppose we need to store a point: 1 data: integer coordinates; 2 functions: get values for the coordinates

More information

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011

CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 Print Your Name: Page 1 of 8 Signature: Aludra Loginname: CSCI 102L - Data Structures Midterm Exam #1 Fall 2011 (10:00am - 11:12am, Wednesday, October 5) Instructor: Bill Cheng Problems Problem #1 (24

More information

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez! C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C Rulez! C++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a

More information

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez!

C++ Mini-Course. Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion. C Rulez! C++ Mini-Course Part 1: Mechanics Part 2: Basics Part 3: References Part 4: Const Part 5: Inheritance Part 6: Libraries Part 7: Conclusion C Rulez! C++ Rulez! C++ Mini-Course Part 1: Mechanics C++ is a

More information

Lecture #1. Introduction to Classes and Objects

Lecture #1. Introduction to Classes and Objects Lecture #1 Introduction to Classes and Objects Topics 1. Abstract Data Types 2. Object-Oriented Programming 3. Introduction to Classes 4. Introduction to Objects 5. Defining Member Functions 6. Constructors

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Introduction to C++ Programming Operator Overloading, Inheritance Lecture 6 February 10, 2005 Fundamentals of Operator Overloading 2 Use operators with objects

More information

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming

Chapter 13: Introduction to Classes Procedural and Object-Oriented Programming Chapter 13: Introduction to Classes 1 13.1 Procedural and Object-Oriented Programming 2 Procedural and Object-Oriented Programming Procedural programming focuses on the process/actions that occur in a

More information

Object-Oriented Programming

Object-Oriented Programming - oriented - iuliana@cs.ubbcluj.ro Babes-Bolyai University 2018 1 / 56 Overview - oriented 1 2 -oriented 3 4 5 6 7 8 Static and friend elements 9 Summary 2 / 56 I - oriented was initially created by Bjarne

More information

Abstract Data Types (ADT) and C++ Classes

Abstract Data Types (ADT) and C++ Classes Abstract Data Types (ADT) and C++ Classes 1-15-2013 Abstract Data Types (ADT) & UML C++ Class definition & implementation constructors, accessors & modifiers overloading operators friend functions HW#1

More information

EL2310 Scientific Programming

EL2310 Scientific Programming (pronobis@kth.se) Overview Overview Wrap Up Introduction to Object Oriented Paradigm More on and Members Operator Overloading Last time Intro to C++ Differences between C and C++ Intro to OOP Today Object

More information

Programming II Lecture 2 Structures and Classes

Programming II Lecture 2 Structures and Classes 3. struct Rectangle { 4. double length; 5. double width; 6. }; 7. int main() 8. { Rectangle R={12.5,7}; 9. cout

More information

pointers & references

pointers & references pointers & references 1-22-2013 Inline Functions References & Pointers Arrays & Vectors HW#1 posted due: today Quiz Thursday, 1/24 // point.h #ifndef POINT_H_ #define POINT_H_ #include using

More information

PIC 10A. Lecture 17: Classes III, overloading

PIC 10A. Lecture 17: Classes III, overloading PIC 10A Lecture 17: Classes III, overloading Function overloading Having multiple constructors with same name is example of something called function overloading. You are allowed to have functions with

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Object Oriented Programming COP3330 / CGS5409

Object Oriented Programming COP3330 / CGS5409 Object Oriented Programming COP3330 / CGS5409 Classes & Objects DDU Design Constructors Member Functions & Data Friends and member functions Const modifier Destructors Object -- an encapsulation of data

More information

10.1 Class Definition. User-Defined Classes. Counter.h. User Defined Types. Counter.h. Counter.h. int, float, char are built into C+ Declare and use

10.1 Class Definition. User-Defined Classes. Counter.h. User Defined Types. Counter.h. Counter.h. int, float, char are built into C+ Declare and use 10.1 Class Definition User-Defined Classes Chapter 10 int, float, char are built into C+ Declare and use int x = 5; Create user defined data types+ Extensive use throughout remainder of course Counter

More information

Outline 2017/03/17. (sections from

Outline 2017/03/17. (sections from Outline 2017/03/17 clarifications I/O basic namespaces and structures (recall) Object Oriented programming (8.1) Classes (8.2 8.6) public, protected and private Constructors and destructors Getters and

More information

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com

More C++ : Vectors, Classes, Inheritance, Templates. with content from cplusplus.com, codeguru.com More C++ : Vectors, Classes, Inheritance, Templates with content from cplusplus.com, codeguru.com 2 Vectors vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes

More information

The Class Construct Part 2

The Class Construct Part 2 The Class Construct Part 2 Lecture 24 Sections 7.7-7.9 Robb T. Koether Hampden-Sydney College Mon, Oct 29, 2018 Robb T. Koether (Hampden-Sydney College) The Class Construct Part 2 Mon, Oct 29, 2018 1 /

More information

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented

More information

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved. Chapter 9 Objects and Classes 1 Objectives Classes & Objects ( 9.2). UML ( 9.2). Constructors ( 9.3). How to declare a class & create an object ( 9.4). Separate a class declaration from a class implementation

More information

Chapter 20 - C++ Virtual Functions and Polymorphism

Chapter 20 - C++ Virtual Functions and Polymorphism Chapter 20 - C++ Virtual Functions and Polymorphism Outline 20.1 Introduction 20.2 Type Fields and switch Statements 20.3 Virtual Functions 20.4 Abstract Base Classes and Concrete Classes 20.5 Polymorphism

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College November 9, 2016 Outline Outline 1 Chapter 9: C++ Classes Outline Chapter 9: C++ Classes 1 Chapter 9: C++ Classes Class Syntax

More information

Chapter 11. The first objective here is to make use of the list class definition from a previous lab. Recall the class definition for ShapeList.

Chapter 11. The first objective here is to make use of the list class definition from a previous lab. Recall the class definition for ShapeList. Chapter 11 A portion of this lab is to be done during the scheduled lab time. The take-home programming assignment is to be turned in before the next lab; see the lab website. The in-lab portion is worth

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 14: Object Oriented Programming in C++ (fpokorny@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Wrap Up Introduction to Object Oriented Paradigm Classes More on Classes

More information

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad

CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING. Dr. Shady Yehia Elmashad CHAPTER 1.2 INTRODUCTION TO C++ PROGRAMMING Dr. Shady Yehia Elmashad Outline 1. Introduction to C++ Programming 2. Comment 3. Variables and Constants 4. Basic C++ Data Types 5. Simple Program: Printing

More information

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year Object Oriented Programming Assistant Lecture Omar Al Khayat 2 nd Year Syllabus Overview of C++ Program Principles of object oriented programming including classes Introduction to Object-Oriented Paradigm:Structures

More information

CSCE 110 PROGRAMMING FUNDAMENTALS

CSCE 110 PROGRAMMING FUNDAMENTALS CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 15. Dictionaries (1): A Key Table Class Prof. amr Goneid, AUC 1 Dictionaries(1): A Key Table Class Prof. Amr Goneid, AUC 2 A Key Table

More information

Introduction to C++ Systems Programming

Introduction to C++ Systems Programming Introduction to C++ Systems Programming Introduction to C++ Syntax differences between C and C++ A Simple C++ Example C++ Input/Output C++ Libraries C++ Header Files Another Simple C++ Example Inline Functions

More information

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

the gamedesigninitiative at cornell university Lecture 7 C++ Overview Lecture 7 Lecture 7 So You Think You Know C++ Most of you are experienced Java programmers Both in 2110 and several upper-level courses If you saw C++, was likely in a systems course Java was based on

More information

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington

CSE 333. Lecture 10 - references, const, classes. Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington CSE 333 Lecture 10 - references, const, classes Hal Perkins Paul G. Allen School of Computer Science & Engineering University of Washington Administrivia New C++ exercise out today, due Friday morning

More information

Unit IV Contents. ECS-039 Object Oriented Systems & C++

Unit IV Contents. ECS-039 Object Oriented Systems & C++ ECS-039 Object Oriented Systems & C++ Unit IV Contents 1 Principles or object oriented programming... 3 1.1 The Object-Oriented Approach... 3 1.2 Characteristics of Object-Oriented Languages... 3 2 C++

More information

Introduction to the C programming language

Introduction to the C programming language Introduction to the C programming language From C to C++: Stack and Queue Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 23, 2010 Outline 1 From struct to classes

More information

CS 162, Lecture 25: Exam II Review. 30 May 2018

CS 162, Lecture 25: Exam II Review. 30 May 2018 CS 162, Lecture 25: Exam II Review 30 May 2018 True or False Pointers to a base class may be assigned the address of a derived class object. In C++ polymorphism is very difficult to achieve unless you

More information

CSc 328, Spring 2004 Final Examination May 12, 2004

CSc 328, Spring 2004 Final Examination May 12, 2004 Name: CSc 328, Spring 2004 Final Examination May 12, 2004 READ THIS FIRST Fill in your name above. Do not turn this page until you are told to begin. Books, and photocopies of pages from books MAY NOT

More information

System Programming. Practical Session 9. C++ classes

System Programming. Practical Session 9. C++ classes System Programming Practical Session 9 C++ classes C++ parameter passing void incval(int n) { //By value n++; void incpoint(int *p) { //By pointer *p = 5; p = 0; void incref(int &n) { //By Reference cout

More information

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING THROUGH C++ Practical: OOPS THROUGH C++ Subject Code: 1618407 PROGRAM NO.1 Programming exercise on executing a Basic C++

More information

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. 1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol. B. Outputs to the console a floating point number f1 in scientific format

More information

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

More information

Module 7 b. -Namespaces -Exceptions handling

Module 7 b. -Namespaces -Exceptions handling Module 7 b -Namespaces -Exceptions handling C++ Namespace Often, a solution to a problem will have groups of related classes and other declarations, such as functions, types, and constants. C++provides

More information

PIC 10A Objects/Classes

PIC 10A Objects/Classes PIC 10A Objects/Classes Ernest Ryu UCLA Mathematics Last edited: November 13, 2017 User-defined types In C++, we can define our own custom types. Object is synonymous to variable, and class is synonymous

More information

Chapter 19 C++ Inheritance

Chapter 19 C++ Inheritance Chapter 19 C++ Inheritance Angela Chih-Wei i Tang Department of Communication Engineering National Central University JhongLi, Taiwan 2009 Fall Outline 19.11 Introduction ti 19.2 Inheritance: Base Classes

More information

PIC 10A. Lecture 15: User Defined Classes

PIC 10A. Lecture 15: User Defined Classes PIC 10A Lecture 15: User Defined Classes Intro to classes We have already had some practice with classes. Employee Time Point Line Recall that a class is like a souped up variable that can store data,

More information

Chapter 19 - C++ Inheritance

Chapter 19 - C++ Inheritance Chapter 19 - C++ Inheritance 19.1 Introduction 19.2 Inheritance: Base Classes and Derived Classes 19.3 Protected Members 19.4 Casting Base-Class Pointers to Derived-Class Pointers 19.5 Using Member Functions

More information

Object-Oriented Programming in C++

Object-Oriented Programming in C++ Object-Oriented Programming in C++ Pre-Lecture 9: Advanced topics Prof Niels Walet (Niels.Walet@manchester.ac.uk) Room 7.07, Schuster Building March 24, 2015 Prelecture 9 Outline This prelecture largely

More information

More C++ : Vectors, Classes, Inheritance, Templates

More C++ : Vectors, Classes, Inheritance, Templates Vectors More C++ : Vectors,, Inheritance, Templates vectors in C++ basically arrays with enhancements indexed similarly contiguous memory some changes defined differently can be resized without explicit

More information

Introduction to the C programming language

Introduction to the C programming language Introduction to the C programming language From C to C++: Stack and Queue Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 23, 2010 Outline 1 From struct to classes

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010 CSE 374 Programming Concepts & Tools Hal Perkins Spring 2010 Lecture 19 Introduction ti to C++ C++ C++ is an enormous language: g All of C Classes and objects (kind of like Java, some crucial differences)

More information

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

More information

Friend Functions, Inheritance

Friend Functions, Inheritance Friend Functions, Inheritance Friend Function Private data member of a class can not be accessed by an object of another class Similarly protected data member function of a class can not be accessed by

More information

Intro. Classes Beginning Objected Oriented Programming. CIS 15 : Spring 2007

Intro. Classes Beginning Objected Oriented Programming. CIS 15 : Spring 2007 Intro. Classes Beginning Objected Oriented Programming CIS 15 : Spring 2007 Functionalia HW 4 Review. HW Out this week. Today: Linked Lists Overview Unions Introduction to Classes // Create a New Node

More information

12/2/2009. The plan. References. References vs. pointers. Reference parameters. const and references. HW7 is out; new PM due date Finish last lecture

12/2/2009. The plan. References. References vs. pointers. Reference parameters. const and references. HW7 is out; new PM due date Finish last lecture The plan 11/30 C++ intro 12/2 C++ intro 12/4 12/7 12/9 12/11 Final prep, evaluations 12/15 Final HW7 is out; new PM due date Finish last lecture David Notkin Autumn 2009 CSE303 Lecture 25 CSE303 Au09 2

More information

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java. Classes Introduce to classes and objects in Java. Classes and Objects in Java Understand how some of the OO concepts learnt so far are supported in Java. Understand important features in Java classes.

More information

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++ CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 19 Introduction to C++ C++ C++ is an enormous language: All of C Classes and objects (kind of like Java, some crucial differences) Many

More information

CS

CS CS 1666 www.cs.pitt.edu/~nlf4/cs1666/ Programming in C++ First, some praise for C++ "It certainly has its good points. But by and large I think it s a bad language. It does a lot of things half well and

More information

Circle all of the following which would make sense as the function prototype.

Circle all of the following which would make sense as the function prototype. Student ID: Lab Section: This test is closed book, closed notes. Points for each question are shown inside [ ] brackets at the beginning of each question. You should assume that, for all quoted program

More information

CSCI 104 Templates. Mark Redekopp David Kempe

CSCI 104 Templates. Mark Redekopp David Kempe 1 CSCI 104 Templates Mark Redekopp David Kempe 2 Overview C++ Templates allow alternate versions of the same code to be generated for various data types FUNCTION TEMPLATES 3 4 How To's Example reproduced

More information

Set Implementation Version 1

Set Implementation Version 1 Introduction to System Programming 234122 Set Implementation Version 1 Masha Nikolski, CS Department, Technion 1 // Version 1.0 2 // Header file for set class. 3 // In this implementation set is a container

More information

CS 376b Computer Vision

CS 376b Computer Vision CS 376b Computer Vision 09 / 25 / 2014 Instructor: Michael Eckmann Today s Topics Questions? / Comments? Enhancing images / masks Cross correlation Convolution C++ Cross-correlation Cross-correlation involves

More information

What is an algorithm?

What is an algorithm? Announcements CS 142 Inheritance/Polymorphism Wrapup Program 8 has been assigned - due Tuesday, Dec. 9 th by 11:55pm 11/21/2014 2 Definitions Class: description of a data type that can contain fields (variables)

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.... COMP6771 Advanced C++ Programming Week 3 Part One: - Overview, and 2016 www.cse.unsw.edu.au/ cs6771 2.... What is Object-based Programming? A class uses data abstraction and encapsulation to define

More information

Praktikum: Entwicklung interaktiver eingebetteter Systeme

Praktikum: Entwicklung interaktiver eingebetteter Systeme Praktikum: Entwicklung interaktiver eingebetteter Systeme C++-Labs (falk@cs.fau.de) 1 Agenda Writing a Vector Class Constructor, References, Overloading Templates, Virtual Functions Standard Template Library

More information

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University (5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University Key Concepts 2 Object-Oriented Design Object-Oriented Programming

More information

Computational Physics

Computational Physics Computational Physics numerical methods with C++ (and UNIX) 2018-19 Fernando Barao Instituto Superior Tecnico, Dep. Fisica email: fernando.barao@tecnico.ulisboa.pt Computational Physics 2018-19 (Phys Dep

More information

Chapter 18 - C++ Operator Overloading

Chapter 18 - C++ Operator Overloading Chapter 18 - C++ Operator Overloading Outline 18.1 Introduction 18.2 Fundamentals of Operator Overloading 18.3 Restrictions on Operator Overloading 18.4 Operator Functions as Class Members vs. as friend

More information

Engineering Tools III: OOP in C++

Engineering Tools III: OOP in C++ Engineering Tools III: OOP in C++ Engineering Tools III: OOP in C++ Why C++? C++ as a powerful and ubiquitous tool for programming of numerical simulations super-computers (and other number-crunchers)

More information

Objectives. INHERITANCE - Part 1. Using inheritance to promote software reusability. OOP Major Capabilities. When using Inheritance?

Objectives. INHERITANCE - Part 1. Using inheritance to promote software reusability. OOP Major Capabilities. When using Inheritance? INHERITANCE - Part 1 OOP Major Capabilities Introduction Basic Concepts and Syntax Protected Members Constructors and Destructors Under Inheritance Multiple Inheritance Common Programming Errors encapsulation

More information

Inheritance and Polymorphism

Inheritance and Polymorphism Inheritance and Polymorphism 1 Inheritance extending a clock to an alarm clock deriving a class 2 Polymorphism virtual functions and polymorphism abstract classes MCS 360 Lecture 8 Introduction to Data

More information

Introduction to Object-Oriented Programming with C++

Introduction to Object-Oriented Programming with C++ Computational Introduction to Object-Oriented ming with C++ 02/19/2009 Outline 1 2 3 4 1 Read Chapter 8 Control logic and iteration 2 s of Section 8.10: Part I, (1) - (11) Due next Tuesday, February 24

More information

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory.

C++ Memory Map. A pointer is a variable that holds a memory address, usually the location of another variable in memory. Pointer C++ Memory Map Once a program is compiled, C++ creates four logically distinct regions of memory: Code Area : Area to hold the compiled program code Data Area : Area to hold global variables Stack

More information

INHERITANCE - Part 1. CSC 330 OO Software Design 1

INHERITANCE - Part 1. CSC 330 OO Software Design 1 INHERITANCE - Part 1 Introduction Basic Concepts and Syntax Protected Members Constructors and Destructors Under Inheritance Multiple Inheritance Common Programming Errors CSC 330 OO Software Design 1

More information

Shahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods

Shahram Rahatlou. Computing Methods in Physics. Overloading Operators friend functions static data and methods Overloading Operators friend functions static data and methods Shahram Rahatlou Computing Methods in Physics http://www.roma1.infn.it/people/rahatlou/cmp/ Anno Accademico 2018/19 Today s Lecture Overloading

More information

SFU CMPT Topic: Classes

SFU CMPT Topic: Classes SFU CMPT-212 2008-1 1 Topic: Classes SFU CMPT-212 2008-1 Topic: Classes Ján Maňuch E-mail: jmanuch@sfu.ca Friday 15 th February, 2008 SFU CMPT-212 2008-1 2 Topic: Classes Encapsulation Using global variables

More information

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance

More information

Informatik I (D-ITET) Übungsstunde 12,

Informatik I (D-ITET) Übungsstunde 12, Informatik I (D-ITET) Übungsstunde 12, 11.12.2017 Hossein Shafagh shafagh@inf.ethz.ch Self-Assessment now! Task 11.1 Finite rings a) struct int_7 { ; int value; //INV: 0

More information

C++ Constructor Insanity

C++ Constructor Insanity C++ Constructor Insanity CSE 333 Spring 2018 Instructor: Justin Hsia Teaching Assistants: Danny Allen Dennis Shao Eddie Huang Kevin Bi Jack Xu Matthew Neldam Michael Poulain Renshu Gu Robby Marver Waylon

More information

Lecture 3 ADT and C++ Classes (II)

Lecture 3 ADT and C++ Classes (II) CSC212 Data Structure - Section FG Lecture 3 ADT and C++ Classes (II) Instructor: Feng HU Department of Computer Science City College of New York @ Feng HU, 2016 1 Outline A Review of C++ Classes (Lecture

More information

CS 162 Intro to CS II. Structs vs. Classes

CS 162 Intro to CS II. Structs vs. Classes CS 162 Intro to CS II Structs vs. Classes 1 Odds and Ends Assignment 1 questions Why does the delete_info have a double pointer to states as a parameter? Do your functions have to be 15 or under? Anymore???

More information

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object

More information

Chapter 15 - C++ As A "Better C"

Chapter 15 - C++ As A Better C Chapter 15 - C++ As A "Better C" Outline 15.1 Introduction 15.2 C++ 15.3 A Simple Program: Adding Two Integers 15.4 C++ Standard Library 15.5 Header Files 15.6 Inline Functions 15.7 References and Reference

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I.

UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I. y UNIVERSITI TEKNIKAL MALAYSIA MELAKA FACULTY INFORMATION TECHNOLOGY AND COMMUNICATION (FTMK) BITE 1513 GAME PROGRAMMING I Lab Module 7 CLASSES, INHERITANCE AND POLYMORPHISM Department of Media Interactive

More information

Midterm Exam 5 April 20, 2015

Midterm Exam 5 April 20, 2015 Midterm Exam 5 April 20, 2015 Name: Section 1: Multiple Choice Questions (24 pts total, 3 pts each) Q1: Which of the following is not a kind of inheritance in C++? a. public. b. private. c. static. d.

More information

const int length = myvector.size(); for(int i = 0; i < length; i++) //...Do something that doesn't modify the length of the vector...

const int length = myvector.size(); for(int i = 0; i < length; i++) //...Do something that doesn't modify the length of the vector... CS106L Winter 2007-2008 Handout #14 Feburary 20, 2008 const Introduction The const keyword is one of C++'s most ubiquitous and unusual features. Normally, C++ compilers will let you get away with almost

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC

CMSC 341 Lecture 6 Templates, Stacks & Queues. Based on slides by Shawn Lupoli & Katherine Gibson at UMBC CMSC 341 Lecture 6 Templates, Stacks & Queues Based on slides by Shawn Lupoli & Katherine Gibson at UMBC Today s Topics Data types in C++ Overloading functions Templates How to implement them Possible

More information

An Introduction to C++

An Introduction to C++ An Introduction to C++ Introduction to C++ C++ classes C++ class details To create a complex type in C In the.h file Define structs to store data Declare function prototypes The.h file serves as the interface

More information

C++ Inheritance. Dr. Md. Humayun Kabir CSE Department, BUET

C++ Inheritance. Dr. Md. Humayun Kabir CSE Department, BUET C++ Inheritance Dr. Md. Humayun Kabir CSE Department, BUET C++ Inheritance Inheritance allows one object to inherit member variables and/or member functions from another object. Inherited object is called

More information

Operator Overloading in C++ Systems Programming

Operator Overloading in C++ Systems Programming Operator Overloading in C++ Systems Programming Operator Overloading Fundamentals of Operator Overloading Restrictions on Operator Overloading Operator Functions as Class Members vs. Global Functions Overloading

More information

Introduction to Programming

Introduction to Programming Introduction to Programming session 6 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Spring 2011 These slides are created using Deitel s slides Sharif University of Technology Outlines

More information

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017

PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017 PROGRAMMING IN C++ KAUSIK DATTA 18-Oct-2017 Objectives Recap C Differences between C and C++ IO Variable Declaration Standard Library Introduction of C++ Feature : Class Programming in C++ 2 Recap C Built

More information