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

Size: px
Start display at page:

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

Transcription

1 In C++, member functions can be defined as part of a struct ADTs in C++ struct Complex { ; void Complex::init(double r, double i) { im = i; int main () { Complex c1, c2; c1.init(3.0, 2.0); c2.init(4.0, 0.0); c1.add(c2); 2 A member function has full access to the member variables of the object that invoked it, without qualification A member function can access the member variables of another object by passing it to the function in the normal way int main () { c1 re = 3.0 im = 2.0 c2 re = 4.0 im = 0.0 int main () { c1 re = im = 2.0 c2 re = 4.0 im = 0.0 Complex c1, c2; c1.init(3.0, 2.0); c2.init(4.0, 0.0); c1.add(c2); Complex c1, c2; c1.init(3.0, 2.0); c2.init(4.0, 0.0); c1.add(c2); void Complex::init(double r, double i) { im = i; 3 4

2 Member functions can be implemented in one of two ways: Inside the class declaration In this case the function is automatically considered inline Outside the class declaration Struct definitions usually appear in a header file Inline functions are also implemented in the header file Ordinary (non-inline) functions are implemented in a source file There are various acceptable extensions:.cpp,.cc or.c struct Complex { void init(double r, double i) { im = i; ; #ifndef COMPLEX_H_ #define COMPLEX_H_ struct Complex { void init(double r, double i) { im = i; ; #endif complex.h #include "complex.h" complex.c 5 6 Unlike C, the struct definition appears in the header file To make sure the user accesses the struct only through the interface, we can control the user's access to specific parts of it Every member of the struct is either public or private Members that are private can only be accessed by functions belonging to the struct struct Complex { private: ; Complex c1, c2; c1.init(3.0, 2.0); c2.init(4.0, 0.0); c1.add(c2); double d = c1.re; We use the private section of the struct to encapsulate our data type as in our ADTs in C But if the struct is defined in the header file, doesn't this break encapsulation? No, encapsulation is not about hiding things from the user, it's about protecting the user from making mistakes However, unlike ADTs in C style, we do not have compile-time encapsulation Adding a field in a struct will require compilation of many files 7 8

3 The class keyword is nearly identical to the struct keyword The difference: the contents of a class are private by default The class keyword is usually used for implementing ADTs From now on, we will refer to our ADTs as classes struct Complex { private: equivalent Each member function must know which object invoked it The compiler implicitly sends a pointer named this to the member function, pointing to the calling object The this pointer is constant it cannot point to another target compilation void add(complex* const this, Complex c) { this-> this-> ; ; c1.add(c2); add(&c1, c2) 9 10 The this pointer can be used within the member function like a normal pointer However, in most cases it is not necessary to use it explicitly A common technique is to have a member function return the object it was invoked for This allows chaining several calls this-> this-> void Complex::init(double re, double im) { this->re = re; this->im = im; Complex c1, c2, c3; c1.add(c2).add(c3); To implement this, we need to return a reference to *this Complex& Complex::add(Complex c) { return *this; Complex Complex::add(Complex c) { return *this; 11 12

4 Some member functions do not modify their object Such member functions should work for const objects as well Declaring const in the end of a member function s prototype will enable it to work on a const object void init(double t, double i); double abs() const; ; void f(complex& c, const Complex& c2) { c.add(c2); c2.add(c); // error cout << c2.abs() << endl; double Complex::abs() const { return sqrt(re * re + im * im); compilation double abs(const Complex* const this) { return sqrt(re * re + im * im); In many cases we will encapsulate a field of a class using two member functions: A getter function for retrieving the value A setter function to allow updating the value Why not just make this variable public? Using a public field prevents us from changing the implementation without changing the interface For example: What if we decide to change Complex to use abs & arg? There are two common naming conventions for such functions: double Complex::getReal() const { return re; void Complex::setReal(double r) { double Complex::real() const { return re; void Complex::real(double r) { A class may have static members and functions A static member is a variable that is part of the class, but does not belong to any specific object Only a single copy of this variable exists The variable exists throughout the life of the program, even if no object is ever created from this class A static member is effectively a global variable But it is part of the class namespace It can be designated as private main.cpp Complex c; c.init(complex::pi / 2.0, 0.0); complex.h static double pi; ; A static variable has to be defined in some source file to actually exist The class only declares the variable Static members are commonly used to define constants needed in the class If the constant is of an integral type (such as int), a definition is not needed complex.h static const double PI; ; complex.cpp const double Complex::PI = ; 15 16

5 A static function is a function which is allowed to access the private parts of the class, but is not invoked by a particular object A static function can be called even if no object has been created A static function does not have access to a this pointer complex.cpp complex.h string Complex::ImaginaryUnit = "i"; static string ImaginaryUnit; void print(complex c) const; static const double PI; static void setimaginaryunit(string s); ; void Complex::print() { cout << re << "+" << im << imaginaryunit; void Complex::setImaginaryUnit(string s) { imaginaryunit = s; Complex c1; c1.init(2.0, 3.0); c1.print(); Complex::setImaginaryUnit("j"); c1.print(); main.cpp The use of functions such as init() is inelegant and error prone The programmer may forget to call it The programmer may call it twice Instead, a special member function called a constructor is used complex.h Complex(double r, double i); ; Complex one(1.0, 0.0); complex.cpp Complex::Complex(double r, double i) { im = i; A constructor has no return value Several constructors can be overloaded with different parameters As with regular functions in C++ Default parameters are also allowed Complex(); Complex(double r, double i = 0); ; void print(const Complex& c) { // implementation Complex c1; // Complex::Complex() Complex c2(2.0, 1.0); // Complex::Complex(r,i) Complex c3(1.0); // Complex::Complex(r,0) Complex c4 = 3.0; // Complex::Complex(r,0) Complex* pc1 = new Complex; // Complex::Complex() Complex* pc2 = new Complex(); // Complex::Complex() Complex* pc3 = new Complex(-3.0, 1.0); // Complex::Complex(r,i) print(complex(0.0, 1.0)); // Complex::Complex(r,i); A constructor which receives no arguments is called a default constructor The default constructor is called when an object is created with no arguments The compiler will automatically generate a default constructor for any class that defines no constructors of its own The compiler-generated default constructor simply calls the default constructors of all the class members Every object is initialized by a constructor! there is an exception for "Plain old data" types, beyond the scope of this course * Complex c1; print(complex()); 19 20

6 When creating an array of objects, the default constructor is called for each of them Complex array1[10]; // Complex::Complex() [x10] Complex* parray = new Complex[10]; // Complex::Complex() [x10] Complex* parray2 = new Complex[10](); // Complex::Complex() [x10] If there is no default constructor available, a compilation error will occur. But how can this happen? If any non-default constructor is explicitly defined, the compiler no longer generates the default constructor automatically This can be solved by adding a default constructor explicitly Exception: Built-in types can be created without initialization This exists for backward-compatibility with C, and efficiency reasons int* parray = new int[10](); // initialize to zeros int* parray2 = new int[10]; // uninitialized In many cases, a constructor will allocate a resource E.g., allocate memory on the heap, open a file, open a network connection, In such a case, the resource must be freed when the object is destroyed Each class has a special member function called a destructor The destructor is automatically invoked when the object is destroyed class Array { int* data; int size; Array(int sz); ~Array(); int& atindex(int index); ; int main() { Array a(10); a.atindex(3) = 2; cout << a.atindex(7) << endl; Array::Array(int sz) { data = new int[sz]; size = sz; Array::~Array() { delete[] data; int& Array::atIndex(int index) { assert(index >= 0 && index < size); return data[index]; Destructors take no arguments Therefore, there can be only one per class A destructor is called whenever an object is released, for example: When a local variable goes out of scope When a dynamically allocated object is explicitly deleted A temporary value is released at the "end of the line" void g(const Array& a); void f() { Array a(10); Array* ptr = new Array(20); Array* ptr2 = new Array(30); g(array(20)); // temporary Array is destructed "at the end of the line" delete ptr; // ptr->~array() is called // a.~array() is called // *ptr2 is leaked! There s a critical difference between initializing an object and assigning a value to it: Initialization occurs when a new object is created Assignment updates the values of an existing object Complex c(1.0, 1.0); Complex c2(c); Complex c3 = c; c = c2; 23 24

7 Lets look again at Array s constructor When are size and data initialized? When an object is created, first its members are initialized, and only then the constructor's body is executed By default, all members are initialized with their default constructors We can use different initialization with an initialization list Syntax for an explicit initialization list Array::Array(int n) { data = new int[n]; size = n; Array::Array(int n) : data(new int[n]), size(n) { // nothing left to do here, that's fine For a type T, the constructor T(const T&) is called the copy constructor This constructor initializes a new object by copying an existing object Array::Array(const Array& array) : data(new int[array.size]), size(array.size) { for (int i = 0; i < size; i++) { data[i] = array.data[i]; The copy constructor is extremely important as it is called whenever an object is passed or returned from a function by value int main() { Array a(10) f(a); g(a); Array b = h(); void f(array a) {... void g(array& a) {... Array h() { return Array(10); The compiler will automatically generate a copy constructor for any class that does not define one explicitly Even if other constructors have been defined The compiler-generated copy constructor simply calls the copy constructors of all the class members If the class uses pointers or allocates resources (such as dynamic memory), a user-defined copy constructor is probably needed When an object is created, its constructor first calls the constructors of all the class members, and only then executes the constructor's body Members are constructed in the order they are defined in the class When an object is destroyed, it s destructor first executes the destructor's body, and then calls the destructors of all of the members Members are destructed in reverse order of creation A compiler-generated copy c'tor for Array will look like this: Array::Array(const Array& array) : data(array.data), size(array.size) { class A { //... A(); ~A(); ; class B { A a1, a2; B() {... ~B() {... ; 27 28

8 We will recreate our set of integers ADT as a class in C++ setcreate, setcopy and setdestroy will be replaced by constructors and destructors We will skip iterators and the filter function for now To get these right in C++ we need operator overloading and templates 1 Array 8 3?? 1, 8, 3 Equal sets 8, 1, 3 #ifndef SET_H_ #define SET_H_ #include <string> class Set { Set(); Set(const Set& set); ~Set(); bool add(int number); bool remove(int number); bool contains(int number) const; int getsize() const; Set unionwith(const Set&) const; Set intersectwith(const Set&) const; set.h (1/2) set.h (2/2) private: int* data; int size; int maxsize; int find(int number) const; void expand(); static const int EXPAND_RATE = 2; static const int INITIAL_SIZE = 10; static const int NUMBER_NOT_FOUND = -1; ; #endif /* SET_H_ */ size maxsize std::string tostring() const; #include "set.h" #include <iostream> using std::cout; using std::endl; int main() { Set set1; Set set2; for (int j = 0; j < 20; j += 2) { set1.add(j); #include "set.h" #include <algorithm> #include <sstream> using std::swap; using std::ostringstream; for (int j = 0; j < 12; j += 3) { set2.add(j); Set unionset = set1.unionwith(set2); Set intersectionset = set2.intersectwith(set2); cout << set1.tostring() << endl; cout << set2.tostring() << endl; cout << unionset.tostring() << endl; cout << intersectionset.tostring() << endl; Set::Set() : data(new int[initial_size]), size(0), maxsize(initial_size) { 31 32

9 Set::Set(const Set& set) : data(new int[set.getsize()]), size(set.getsize()), maxsize(set.getsize()) { for(int i = 0; i < size; i++) { data[i] = set.data[i]; Set::~Set() { int Set::find(int number) const { for(int i = 0; i < size; i++) { if (data[i] == number) { return i; return NUMBER_NOT_FOUND; bool Set::contains(int number) const { return find(number)!= NUMBER_NOT_FOUND; delete[] data; int Set::getSize() const { return size; void Set::expand() { int newsize = maxsize * EXPAND_RATE; int* newdata = new int[newsize]; for (int i = 0; i < size; ++i) { bool Set::add(int number) { if (contains(number)) { return false; if (size >= maxsize) { expand(); newdata[i] = data[i]; delete[] data; data[size++] = number; return true; data = newdata; maxsize = newsize; bool Set::remove(int number) { int index = find(number); if (index == NUMBER_NOT_FOUND) { return false; data[index] = data[--size]; return true; 35 36

10 37 Set Set::unionWith(const Set& set) const { Set result = set; for (int i = 0; i < size; ++i) { result.add(data[i]); return result; Set Set::intersectWith(const Set& set) const { Set result; for (int i = 0; i < size; ++i) { if (set.contains(data[i])) { result.add(data[i]); return result; we will see in the next lecture a more * common way of enabling printing of a class 38 std::string Set::toString() const { ostringstream os; os << "{"; for(int i = 0; i < size; i++) { if (i > 0 ) { os << ","; os << " " << data[i]; os << " "; return os.str(); There is a difference between copying and assignment int main() { Set set1; Set set2; for (int j = 0; j < 20; j += 2) { set1.add(j); set2 = set1; To solve this problem we need to overload operator= Overloading operators is discussed next Within C++, there is a much smaller and cleaner language struggling to get out. - Bjarne Stroustrup 39 40

Class Destructors constant member functions

Class Destructors constant member functions Dynamic Memory Management Class Destructors constant member functions Shahram Rahatlou Corso di Programmazione++ Roma, 6 April 2009 Using Class Constructors #include Using std::vector; Datum average(vector&

More information

Chapter 10 Introduction to Classes

Chapter 10 Introduction to Classes C++ for Engineers and Scientists Third Edition Chapter 10 Introduction to Classes CSc 10200! Introduction to Computing Lecture 20-21 Edgardo Molina Fall 2013 City College of New York 2 Objectives In this

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

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

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

Defining new types and interfaces

Defining new types and interfaces Defining new types and interfaces Assume we need complex numbers in our software We create the following struct: typedef struct { double real; double imag; Complex; Is this enough? No! 2 What do we want

More information

Lecture 18 Tao Wang 1

Lecture 18 Tao Wang 1 Lecture 18 Tao Wang 1 Abstract Data Types in C++ (Classes) A procedural program consists of one or more algorithms that have been written in computerreadable language Input and display of program output

More information

Roxana Dumitrescu. C++ in Financial Mathematics

Roxana Dumitrescu. C++ in Financial Mathematics Roxana Dumitrescu C++ in Financial Mathematics What have we learnt? Arrays; relation between arrays and pointers.. Returning arrays from functions Passing arrays to functions Intoduction to classes Plan

More information

Function Overloading

Function Overloading Function Overloading C++ supports writing more than one function with the same name but different argument lists How does the compiler know which one the programmer is calling? They have different signatures

More information

COMP 2355 Introduction to Systems Programming

COMP 2355 Introduction to Systems Programming COMP 2355 Introduction to Systems Programming Christian Grothoff christian@grothoff.org http://grothoff.org/christian/ 1 Today Class syntax, Constructors, Destructors Static methods Inheritance, Abstract

More information

Lecture 7. Log into Linux New documents posted to course webpage

Lecture 7. Log into Linux New documents posted to course webpage Lecture 7 Log into Linux New documents posted to course webpage Coding style guideline; part of project grade is following this Homework 4, due on Monday; this is a written assignment Project 1, due next

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

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

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

Classes and Objects. Class scope: - private members are only accessible by the class methods. Class Declaration Classes and Objects class class-tag //data members & function members ; Information hiding in C++: Private Used to hide class member data and methods (implementation details). Public

More information

Intermediate Programming, Spring 2017*

Intermediate Programming, Spring 2017* 600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general

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

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis

C++ Programming. Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis C++ Programming Classes, Constructors, Operator overloading (Continued) M1 Math Michail Lampis michail.lampis@dauphine.fr Classes These (and the previous) slides demonstrate a number of C++ features related

More information

Classes. Christian Schumacher, Info1 D-MAVT 2013

Classes. Christian Schumacher, Info1 D-MAVT 2013 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

More information

A brief introduction to C++

A brief introduction to C++ A brief introduction to C++ Rupert Nash r.nash@epcc.ed.ac.uk 13 June 2018 1 References Bjarne Stroustrup, Programming: Principles and Practice Using C++ (2nd Ed.). Assumes very little but it s long Bjarne

More information

beginslide Chapter 6 The C++ Programming Language The Role of Classes

beginslide Chapter 6 The C++ Programming Language The Role of Classes 1 Chapter 6 The C++ Programming Language The Role of Classes 2 C++ as Enhanced C Stronger typing. Inline functions. Call by reference. Function prototypes and overloading. Default function parameters.

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

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

Programming in C and C++

Programming in C and C++ Programming in C and C++ 5. C++: Overloading, Namespaces, and Classes Dr. Neel Krishnaswami University of Cambridge (based on notes from and with thanks to Anil Madhavapeddy, Alan Mycroft, Alastair Beresford

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

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

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

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

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

CS201- Introduction to Programming Current Quizzes

CS201- Introduction to Programming Current Quizzes CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

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

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

G52CPP C++ Programming Lecture 13

G52CPP C++ Programming Lecture 13 G52CPP C++ Programming Lecture 13 Dr Jason Atkin http://www.cs.nott.ac.uk/~jaa/cpp/ g52cpp.html 1 Last lecture Function pointers Arrays of function pointers Virtual and non-virtual functions vtable and

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

Implementing Abstract Data Types (ADT) using Classes

Implementing Abstract Data Types (ADT) using Classes Implementing Abstract Data Types (ADT) using Classes Class Definition class classname { public: //public member functions private: //private data members and member functions }; // Note the semicolon!

More information

CSE 303: Concepts and Tools for Software Development

CSE 303: Concepts and Tools for Software Development CSE 303: Concepts and Tools for Software Development Hal Perkins Autumn 2008 Lecture 24 Introduction to C++ CSE303 Autumn 2008, Lecture 24 1 C++ C++ is an enormous language: All of C Classes and objects

More information

GEA 2017, Week 4. February 21, 2017

GEA 2017, Week 4. February 21, 2017 GEA 2017, Week 4 February 21, 2017 1. Problem 1 After debugging the program through GDB, we can see that an allocated memory buffer has been freed twice. At the time foo(...) gets called in the main function,

More information

04-19 Discussion Notes

04-19 Discussion Notes 04-19 Discussion Notes PIC 10B Spring 2018 1 Constructors and Destructors 1.1 Copy Constructor The copy constructor should copy data. However, it s not this simple, and we need to make a distinction here

More information

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

C++ C and C++ C++ fundamental types. C++ enumeration. To quote Bjarne Stroustrup: 5. Overloading Namespaces Classes C++ C and C++ 5. Overloading Namespaces Classes Alastair R. Beresford University of Cambridge Lent Term 2007 To quote Bjarne Stroustrup: C++ is a general-purpose programming language with a bias towards

More information

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2

Copying Data. Contents. Steven J. Zeil. November 13, Destructors 2 Steven J. Zeil November 13, 2013 Contents 1 Destructors 2 2 Copy Constructors 11 2.1 Where Do We Use a Copy Constructor? 12 2.2 Compiler-Generated Copy Constructors............................................

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

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

Classes: A Deeper Look

Classes: A Deeper Look Classes: A Deeper Look 1 Introduction Implementing a Time Abstract Data Type with a class Class Scope and Accessing Class Members Separating Interface from Implementation Controlling Access to Members

More information

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012

MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012 MARKING KEY The University of British Columbia MARKING KEY Computer Science 260 Midterm #1 Examination 12:30 noon, Tuesday, February 14, 2012 Instructor: K. S. Booth Time: 70 minutes (one hour ten minutes)

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

Constructor - example

Constructor - example Constructors A constructor is a special member function whose task is to initialize the objects of its class. It is special because its name is same as the class name. The constructor is invoked whenever

More information

Object Oriented Software Design II

Object Oriented Software Design II Object Oriented Software Design II Introduction to C++ Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa February 20, 2012 G. Lipari (Scuola Superiore Sant Anna) C++ Intro February

More information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

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

Structures and Member Functions

Structures and Member Functions Structures and Member Functions We ve used structures before to enable us to group variables together to make our lives easier when programming C++ allows us to use functions within structures We create

More information

Introduction to Programming session 24

Introduction to Programming session 24 Introduction to Programming session 24 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2010 These slides are created using Deitel sslides Sharif Universityof Technology Outlines Introduction

More information

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil

More About Classes. Gaddis Ch. 14, CS 2308 :: Fall 2015 Molly O'Neil More About Classes Gaddis Ch. 14, 13.3 CS 2308 :: Fall 2015 Molly O'Neil Pointers to Objects Just like pointers to structures, we can define pointers to objects Time t1(12, 20, true); Time *tptr; tptr

More information

Where do we go from here?

Where do we go from here? Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons

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

การทดลองท 8_2 Editor Buffer Array Implementation

การทดลองท 8_2 Editor Buffer Array Implementation การทดลองท 8_2 Editor Buffer Array Implementation * File: buffer.h * -------------- * This file defines the interface for the EditorBuffer class. #ifndef _buffer_h #define _buffer_h * Class: EditorBuffer

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

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1. COMP6771 Advanced C++ Programming Week 4 Part One: (continued) and 2016 www.cse.unsw.edu.au/ cs6771 2. Inline Constructors, Accessors and Mutators Question (from 2015): In the week 3 examples, constructors

More information

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND

l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains the following: - variables AND Introduction to Classes 13.2 The Class Unit 4 Chapter 13 CS 2308 Fall 2016 Jill Seaman 1 l A class in C++ is similar to a structure. - It allows you to define a new (composite) data type. l A class contains

More information

Midterm Review. PIC 10B Spring 2018

Midterm Review. PIC 10B Spring 2018 Midterm Review PIC 10B Spring 2018 Q1 What is size t and when should it be used? A1 size t is an unsigned integer type used for indexing containers and holding the size of a container. It is guarenteed

More information

CE221 Programming in C++ Part 1 Introduction

CE221 Programming in C++ Part 1 Introduction CE221 Programming in C++ Part 1 Introduction 06/10/2017 CE221 Part 1 1 Module Schedule There are two lectures (Monday 13.00-13.50 and Tuesday 11.00-11.50) each week in the autumn term, and a 2-hour lab

More information

Pointers. Developed By Ms. K.M.Sanghavi

Pointers. Developed By Ms. K.M.Sanghavi Pointers Developed By Ms. K.M.Sanghavi Memory Management : Dynamic Pointers Linked List Example Smart Pointers Auto Pointer Unique Pointer Shared Pointer Weak Pointer Memory Management In order to create

More information

Overloading Operators in C++

Overloading Operators in C++ Overloading Operators in C++ C++ allows the programmer to redefine the function of most built-in operators on a class-by-class basis the operator keyword is used to declare a function that specifies what

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

CS 11 C++ track: lecture 1

CS 11 C++ track: lecture 1 CS 11 C++ track: lecture 1 Administrivia Need a CS cluster account http://www.cs.caltech.edu/cgi-bin/ sysadmin/account_request.cgi Need to know UNIX (Linux) www.its.caltech.edu/its/facilities/labsclusters/

More information

B16 Object Oriented Programming

B16 Object Oriented Programming B16 Object Oriented Programming Michael A. Osborne mosb@robots.ox.ac.uk http://www.robots.ox.ac.uk/~mosb/teaching.html#b16 Hilary 2013 Topic 4: Constructors Recall our definition of the Complex class.

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

B16 Object Oriented Programming

B16 Object Oriented Programming B16 Object Oriented Programming Michael A Osborne mosb@robots.ox.ac.uk http://www.robots.ox.ac.uk/~mosb/b16.html Hilary 2014 Topic 4: Constructors Recall our definition of the Complex class. class Complex

More information

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform Ch 13: Introduction to Classes 13.1 Procedural Programming Data is stored in variables CS 2308 Spring 2014 Jill Seaman - Perhaps using arrays and structs. Program is a collection of functions that perform

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 14: Object Oriented Programming in C++ (ramviyas@kth.se) Overview Overview Lecture 14: Object Oriented Programming in C++ Classes (cont d) More on Classes and Members Group presentations Last time

More information

Practice Problems CS2620 Advanced Programming, Spring 2003

Practice Problems CS2620 Advanced Programming, Spring 2003 Practice Problems CS2620 Advanced Programming, Spring 2003 April 9, 2003 1. Explain the results of each vector definition: string pals[] = "pooh", "tigger", "piglet", "eeyore", "kanga" a) vector

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

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III

Distributed Real-Time Control Systems. Lecture 14 Intro to C++ Part III Distributed Real-Time Control Systems Lecture 14 Intro to C++ Part III 1 Class Hierarchies The human brain is very efficient in finding common properties to different entities and classify them according

More information

A Tour of the C++ Programming Language

A Tour of the C++ Programming Language A Tour of the C++ Programming Language We already know C Everything that can be done with a computer, can be done in C Why should we learn another language? Newer languages provide a bigger toolbox Some

More information

CPSC 427: Object-Oriented Programming

CPSC 427: Object-Oriented Programming CPSC 427: Object-Oriented Programming Michael J. Fischer Lecture 7 September 21, 2016 CPSC 427, Lecture 7 1/21 Brackets Example (continued) Storage Management CPSC 427, Lecture 7 2/21 Brackets Example

More information

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University

(5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University (5 2) Introduction to Classes in C++ Instructor - Andrew S. O Fallon CptS 122 (February 7, 2018) Washington State University Key Concepts Function templates Defining classes with member functions The Rule

More information

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor

Outline. User-dened types Categories. Constructors. Constructors. 4. Classes. Concrete classes. Default constructor. Default constructor Outline EDAF50 C++ Programming 4. Classes Sven Gestegård Robertz Computer Science, LTH 2018 1 Classes the pointer this const for objects and members Copying objects friend inline 4. Classes 2/1 User-dened

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

UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors

UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors UEE1303(1070) S12: Object-Oriented Programming Constructors and Destructors What you will learn from Lab 5 In this laboratory, you will learn how to use constructor and copy constructor to create an object

More information

CS3157: Advanced Programming. Outline

CS3157: Advanced Programming. Outline CS3157: Advanced Programming Lecture #12 Apr 3 Shlomo Hershkop shlomo@cs.columbia.edu 1 Outline Intro CPP Boring stuff: Language basics: identifiers, data types, operators, type conversions, branching

More information

Come and join us at WebLyceum

Come and join us at WebLyceum Come and join us at WebLyceum For Past Papers, Quiz, Assignments, GDBs, Video Lectures etc Go to http://www.weblyceum.com and click Register In Case of any Problem Contact Administrators Rana Muhammad

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

OBJECT ORIENTED PROGRAMMING USING C++

OBJECT ORIENTED PROGRAMMING USING C++ OBJECT ORIENTED PROGRAMMING USING C++ Abstract Data Types and Encapsulation Concepts ISBN 0-321-33025-0 Chapter 11 Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform

! Data is stored in variables. - Perhaps using arrays and structs. ! Program is a collection of functions that perform Ch 13: Introduction to Classes 13.1 Procedural Programming! Data is stored in variables CS 2308 Spring 2015 Jill Seaman - Perhaps using arrays and structs.! Program is a collection of functions that perform

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

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

Abstraction in Software Development

Abstraction in Software Development Abstract Data Types Programmer-created data types that specify values that can be stored (type of data) operations that can be done on the values The user of an abstract data type (ADT) does not need to

More information

EECE.3220: Data Structures Spring 2017

EECE.3220: Data Structures Spring 2017 EECE.3220: Data Structures Spring 2017 Lecture 14: Key Questions February 24, 2017 1. Describe the characteristics of an ADT to store a list. 2. What data members would be necessary for a static array-based

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

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

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I

See the CS 2704 notes on C++ Class Basics for more details and examples. Data Structures & OO Development I Polynomial Class Polynomial(); Polynomial(const string& N, const vector& C); Polynomial operator+(const Polynomial& RHS) const; Polynomial operator-(const Polynomial& RHS) const; Polynomial operator*(const

More information

A Tour of the C++ Programming Language

A Tour of the C++ Programming Language A Tour of the C++ Programming Language We already know C Everything that can be done with a computer, can be done in C Why should we learn another language? Newer languages provide a bigger toolbox Some

More information

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator

C++ Addendum: Inheritance of Special Member Functions. Constructors Destructor Construction and Destruction Order Assignment Operator C++ Addendum: Inheritance of Special Member Functions Constructors Destructor Construction and Destruction Order Assignment Operator What s s Not Inherited? The following methods are not inherited: Constructors

More information

CMSC 4023 Chapter 11

CMSC 4023 Chapter 11 11. Topics The Concept of Abstraction Introduction to Data Abstraction Design Issues for Abstract Data Types Language Examples Parameterized Abstract Data Types Encapsulation Constructs Naming Encapsulations

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

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

Abstract Data Types and Encapsulation Concepts

Abstract Data Types and Encapsulation Concepts Abstract Data Types and Encapsulation Concepts The Concept of Abstraction An abstraction is a view or representation of an entity that includes only the most significant attributes The concept of abstraction

More information

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay C++ Basics Data Processing Course, I. Hrivnacova, IPN Orsay The First Program Comments Function main() Input and Output Namespaces Variables Fundamental Types Operators Control constructs 1 C++ Programming

More information