Classes. Christian Schumacher, Info1 D-MAVT 2013

Similar documents
Object Oriented Software Design II

CS304 Object Oriented Programming Final Term

And Even More and More C++ Fundamentals of Computer Science

eingebetteter Systeme

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

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Overloading Operators in C++


Object Oriented Programming. Solved MCQs - Part 2

Instantiation of Template class

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

C++ (Non for C Programmer) (BT307) 40 Hours

Roxana Dumitrescu. C++ in Financial Mathematics

Function Overloading

ADTs in C++ In C++, member functions can be defined as part of a struct

C++ Important Questions with Answers

B16 Object Oriented Programming

Part VII. Object-Oriented Programming. Philip Blakely (LSC) C++ Introduction 194 / 370

Recharge (int, int, int); //constructor declared void disply();

An Introduction to C++

B16 Object Oriented Programming

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes

Lecture 18 Tao Wang 1

EL2310 Scientific Programming

COMP 2355 Introduction to Systems Programming

C++ Inheritance and Encapsulation

Kapil Sehgal PGT Computer. Science Ankleshwar Gujarat

VB.NET. Exercise 1: Creating Your First Application in Visual Basic.NET

AIMS Embedded Systems Programming MT 2017

Inheritance, and Polymorphism.

STUDY NOTES UNIT 1 - INTRODUCTION TO OBJECT ORIENTED PROGRAMMING

Object-Oriented Programming

CHAPTER 1 Introduction to Computers and Programming CHAPTER 2 Introduction to C++ ( Hexadecimal 0xF4 and Octal literals 031) cout Object

Programming in C and C++

COMS W3101 Programming Language: C++ (Fall 2016) Ramana Isukapalli

Where do we go from here?

CS304 Object Oriented Programming

Object-Oriented Programming

Interview Questions of C++

CS201 Some Important Definitions

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

C++ PROGRAMMING LANGUAGE: CLASSES. CAAM 519, CHAPTER 13

6.096 Introduction to C++ January (IAP) 2009

Evolution of Programming Languages

Object-Oriented Programming for Scientific Computing

C++ Inheritance and Encapsulation

CLASSES AND OBJECTS IN JAVA

Data Abstraction. Hwansoo Han

QUIZ on Ch.5. Why is it sometimes not a good idea to place the private part of the interface in a header file?

CSE 143. Linked Lists. Linked Lists. Manipulating Nodes (1) Creating Nodes. Manipulating Nodes (3) Manipulating Nodes (2) CSE 143 1

Chapter 11. Abstract Data Types and Encapsulation Concepts

CS201- Introduction to Programming Current Quizzes

CSC 210, Exam Two Section February 1999

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

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

More Advanced Class Concepts

CSC 330 Object Oriented Programming. Operator Overloading Friend Functions & Forms

BSM550 C Programming Language

6.096 Introduction to C++

INHERITANCE - Part 1. CSC 330 OO Software Design 1

Question: How can we compare two objects of a given class to see if they are the same? Is it legal to do: Rectangle r(0,0,3,3);,, Rectangle s(0,0,4,4)

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 12: Classes and Data Abstraction

Special Member Functions

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

OBJECT ORIENTED PROGRAMMING. Ms. Ajeta Nandal C.R.Polytechnic,Rohtak

Classes and Objects. Class scope: - private members are only accessible by the class methods.

Outline. Dynamic Memory Classes Dynamic Memory Errors In-class Work. 1 Chapter 10: C++ Dynamic Memory

Implementing Abstract Data Types (ADT) using Classes

Chapter 10 Introduction to Classes

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

G52CPP C++ Programming Lecture 13

C++ (classes) Hwansoo Han

Advanced Systems Programming

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

AN OVERVIEW OF C++ 1

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

Reference Parameters A reference parameter is an alias for its corresponding argument in the function call. Use the ampersand (&) to indicate that



Special Member Functions. Compiler-Generated Destructor. Compiler-Generated Default Constructor. Special Member Functions

Jayaram college of Engineering and Technology, Pagalavadi. CS2203 Object Oriented Programming Question Bank Prepared By: S.Gopalakrishnan, Lecturer/IT

Common Misunderstandings from Exam 1 Material

Programming, numerics and optimization

Short Notes of CS201

Introduction to Programming Using Java (98-388)

CGS 2405 Advanced Programming with C++ Course Justification

Pointers, Dynamic Data, and Reference Types

STRUCTURING OF PROGRAM

SFU CMPT Topic: Has-a Relationship

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

CS201 - Introduction to Programming Glossary By

Object Oriented Design

Topic 10: Introduction to OO analysis and design

IS0020 Program Design and Software Tools Midterm, Fall, 2004

Object Oriented Programming in C#

Object-Oriented Programming. Lecture 2 Dr Piotr Cybula

Transcription:

Classes Christian Schumacher, chschuma@inf.ethz.ch Info1 D-MAVT 2013 Object-Oriented Programming Defining and using classes Constructors & destructors Operators friend, this, const

Example Student management system Students consist of different types of data (name, age, courses) Can be modeled as struct struct Student char* name; int age; int courses[50]; bool ismaster; bool isimmatriculated; }; name = "Bob" age = 21 courses = 2, 4 } ismaster = false isimmatriculated = true name = "John" age = 24 courses = 7, 10, 12, 33, 71 } ismaster = true isimmatriculated = true 2

Example Function to change student status has to have student passed as argument void exmatriculate(student &s) s.isimmatriculated = false; struct Student char* name; int age; int courses[50]; bool ismaster; bool isimmatriculated; }; } Function is specific to Student data type, but defined separately Connection of data and functionality should be reflected in code CLASSES 3

Object-Oriented Programming Abstraction model problems with multiple objects that interact Encapsulation & Data Hiding hide complex implementation Inheritance design new classes using already existing member variables and functions of already defined classes Polymorphism write a function to compare fruits and the program decides which function to call based on whether you compare oranges or apples Reusability and code modularity 4

General Remarks Classes exist only in C++, not in C Classes (class) consists of: Set of member variables (like struct) Set of member functions (so-called methods) Defines visibility of members (public / private) Main difference to structs: In classes, member access is private, if not otherwise specified In structs, member access is public, if not otherwise specified 5

Defining Classes class keyword identifies class definition Name of the class private keyword defines class members that can be accessed only by the class public keyword defines class members that can be accessed by everyone class Complex private: double real; double imag; public: void set(double r, double i); }; 6

Object Declaration After declaring a class, it is available as a new type We can use it to define variables The instance of a class is called «object» Complex number1; Complex number2; We can also call the public member functions number1.set(1, 0); number2.set(4.93, -1); Syntax: object.function_name(argument); 7

Calling member functions Objects can also be created with new Complex* cptr = new Complex; Dereferencing with * (*cptr).set(3.0, 2.0); Shortcut using -> cptr->set(3.0, 2.0); Syntax: object_pointer->function_name(argument); 8

Implementing Member Functions So far we only defined the member functions. To define what they do we need to implement them Member functions are basically regular functions, but we have to use the scope operator to define to which class they belong void Complex::set(double r, double i) real = r; } imag = i; Implementation of the «set» member function of class «Complex» Member functions can use all private member of the class they belong to 9

Header Files Usally the class is written in two separate files: Header file complex.h Definition of members class Complex private: double real; double imag; Body file complex.cpp Includes complex.h Implementation of member functions public: void set(double r, double i); }; #include "complex.h" void Complex::set(double r, double i) real = r; imag = i; } 10

Constructors How to initialize objects? Structs were initialized as follows: Student stud = Hans, Heiri, 13123456 }; For classes this is not possible anymore since private member variables cannot be accessed from outside anymore! Solution: The object has to initialize itself when created 11

Constructors Constructors are methods which are automatically called when an object is created. The default constructor always exists: Complex c; Complex d = Complex(); If not redefined, it initializes all member variables with their own default constructor Can have multiple constructors for increased flexibility 12

Constructors Default constructor can be redefined The constructor is a special member function with no return type and the same name as the class class Complex private: double real; double imag; Complex.h public: Complex(); void set(double r, double i); }; Complex::Complex() real = 1; imag = 0; } Complex.cpp 13

Constructors Constructors can also take arguments Complex.h class Complex private: double real; double imag; Complex::Complex(double r, double i) real = r; imag = i; } Complex.cpp public: Complex(); Complex(double r, double i); void set(double r, double i); }; Calling the new constructor: Complex c1 = Complex(1.0, 2.0); Complex c2(1.0, 2.0); Every definition of a constructor turns default constructor invalid Redefine the default constructor yourself 14

Destructors Second type of special member functions Called automatically when an object is destroyed Destructors can be used to clean up memory that was allocated by the class and is not used anymore Complex.h class Complex private: double real; double imag; Complex::~Complex() // destroy the world. } Complex.cpp public: Complex(); Complex(double r, double i); ~Complex(); void set(double r, double i); }; Only one destructor for each class Has the same name as the class with a tilde ~ in front. Destructors have no return value and no arguments. 15

Destructors Calling destructors Automatically called during delete Complex *c = new Complex;... delete c; Called at end of scope in which object was created Complex c;... // --> call to destructor of `c` } // --> end of scope of `c` 16

const Indicates that no data is modified Variables: int j = 5, k = 6; const int i = 1; i = 2; // ERROR int * const i = &j; i = &k; //ERROR *i = k; //ok Functions: Return value is const Parameter is const Function is const const Complex getsum(const Complex a) const; no members variables are modified can call only other const methods 17

this & friend this Pointer to the current object Friends Allow access to private functions and variables from other classes Complex::Complex(double real, double imag2) this->real = real; // this necessary imag = imag2; // this not necessary } class Complex public: friend void myfunction(); // friend function friend class MyClass; // friend class } myfunction can access private members of Complex All member functions of MyClass can access private members of Complex 18

Operators Interaction between objects Could be solved this way: Complex c(8.3, 2.4); Complex d(0.5, 4.1); c.add(d); c.sub(d); c.mult(d); c.div(d); //Member functions that implement //the four basic arithmetic //operations But would be cool to use it this way: Complex e; e = c + d; e = c d; e = c * d; e = c / d; 19

Operators Operators (+, *, ) can be defined, just like functions Use const to indicate immutability The operands should not be changed by accident! class Complex private: double real; double imag; public: void set(double r, double i); Complex operator+(const Complex &c2) const; }; Complex Complex::operator+(const Complex &c2) const Complex sum; sum.real = real + c2.real; sum.imag = imag + c2.imag; return sum; } 20

Operators Now the addition operator can be used Complex a; Complex b; // Call as operator: Complex s1 = a + b; Or the operator can be called as a normal function // call as function: Complex s2 = a.operator+(b); 21