C++#Overview#(1)# Topics# COS320# Heejin#Ahn#

Similar documents
C++ Overview (1) COS320 Heejin Ahn

Where do we go from here?

W3101: Programming Languages C++ Ramana Isukapalli

Evolution of Programming Languages

CSC1322 Object-Oriented Programming Concepts

G52CPP C++ Programming Lecture 13

Fundamentals of Programming. Lecture 19 Hamed Rasifard

COMP 2355 Introduction to Systems Programming

Laboratorio di Tecnologie dell'informazione

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

Classes in C++98 and C++11

Laboratorio di Tecnologie dell'informazione. Ing. Marco Bertini

Dr. Md. Humayun Kabir CSE Department, BUET

Where do we go from here?

CS3157: Advanced Programming. Outline

ECE 3574: Dynamic Polymorphism using Inheritance

Instantiation of Template class

class Polynomial { public: Polynomial(const string& N = "no name", const vector<int>& C = vector<int>());... };

pointers & references

Object Oriented Software Design II

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Advanced C++ Programming Workshop (With C++11, C++14, C++17) & Design Patterns

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

Tokens, Expressions and Control Structures

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

Object Oriented Programming: Inheritance Polymorphism

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

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

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

CS250 Final Review Questions

Data Abstraction. Hwansoo Han

C++ Important Questions with Answers

C++ Coding Standards and Practices. Tim Beaudet March 23rd 2015

OBJECT ORIENTED PROGRAMMING USING C++

G52CPP C++ Programming Lecture 15

Chapter 11. Abstract Data Types and Encapsulation Concepts

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued

the gamedesigninitiative at cornell university Lecture 7 C++ Overview

CS250 Final Review Questions

Pointers, Dynamic Data, and Reference Types

Chapter 11. Abstract Data Types and Encapsulation Concepts ISBN

Where do we stand on inheritance?

From Java to C++ From Java to C++ CSE250 Lecture Notes Weeks 1 2, part of 3. Kenneth W. Regan University at Buffalo (SUNY) September 10, 2009

Welcome to Teach Yourself Acknowledgments Fundamental C++ Programming p. 2 An Introduction to C++ p. 4 A Brief History of C++ p.

Assignment operator string class c++ Assignment operator string class c++.zip

Resource Management With a Unique Pointer. Resource Management. Implementing a Unique Pointer Class. Copying and Moving Unique Pointers

COMP322 - Introduction to C++

Introduction to the C programming language

CSE 303: Concepts and Tools for Software Development

CS250 Final Review Questions

Programming C++ Lecture 5. Howest, Fall 2013 Instructor: Dr. Jennifer B. Sartor

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

Introduction to the C programming language


CS24 Week 3 Lecture 1

Short Notes of CS201

Increases Program Structure which results in greater reliability. Polymorphism

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

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

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

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

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

PHY4321 Summary Notes

C++ Casts and Run-Time Type Identification

CS201 - Introduction to Programming Glossary By

AN OVERVIEW OF C++ 1

Extending Classes (contd.) (Chapter 15) Questions:

Lecture-5. Miscellaneous topics Templates. W3101: Programming Languages C++ Ramana Isukapalli

12. A bit of C++ Oscar Nierstrasz. Friday, October 21, 11

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

G52CPP C++ Programming Lecture 20

Programming in C++: Programming Test-2

CS 103 Unit 10 Slides

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

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

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

Fast Introduction to Object Oriented Programming and C++

Object-oriented Programming in C++

CS 103 Unit 10 Slides

Friend Functions and Friend Classes

Constants, References

2 ADT Programming User-defined abstract data types

Object-Oriented Programming, Iouliia Skliarova

Abstract Data Types and Encapsulation Concepts

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

21. Dynamic Datatypes and Memory Management

Introduction to C++ Systems Programming

Inheritance, and Polymorphism.

Module 9. Templates & STL

SFU CMPT Topic: Class Templates

Abstract Data Types (ADTs) 1. Legal Values. Client Code for Rational ADT. ADT Design. CS 247: Software Engineering Principles

C++ Functions. Procedural-based Programming. what s a functions

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

C++ Inheritance II, Casting

COMP6771 Advanced C++ Programming

A Tour of the C++ Programming Language

21. Dynamic Datatypes and Memory Management

Introduction to Programming

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Preface to the Second Edition Preface to the First Edition Brief Contents Introduction to C++ p. 1 A Review of Structures p.

Transcription:

Created#by#Bjarne#Stroustrup# Introduc@on# C++#Overview#(1)# COS320# Heejin#Ahn# (heejin@cs.princeton.edu)# Standards# C++98,#C++03,#C++07,#C++11,#and#C++14# Features# Classes#and#objects# Operator#overloading# Templates# STL#(Standard#Template#Library)# # S@ll#widely#used#in#performanceRcri@cal#programs# This#overview#assumes#that#you#know#C#and#Java# C++#is#a#Federa@on#of#Languages# C# Mostly#backward#compa@ble#with#C# Blocks,#statements,#preprocessor,#builtRin#data#types,#arrays,#pointers,# # ObjectROriented#C++# Classes,#encapsula@on,#inheritance,#polymorphism,#virtual#func@ons,## Template#C++# Paradigm#for#generic#programming# STL#(Standard#Template#Library)# Generic#library#using#templates# Containers,#iterators,#algorithms,#func@on#objects## from#[3]# Today# Heap#memory#alloca@on# References# Classes# Inheritance# Next#@me# Operator#overloading# I/O#streams# Templates# STL# C++11# Topics#

Heap#alloca@on:#new#and#delete from#[1]# new/delete#is#a#typersafe#alterna@ve#to#malloc/free# new#t#allocates#an#object#of#type#t#on#heap,#returns#pointer#to#it# Stack *sp = new Stack(); new#t[n]#allocates#array#of#t's#on#heap,#returns#pointer#to#first# int *stk = new int[100]; By#default,#throws#excep@on#if#no#memory## delete#p#frees#the#single#item#pointed#to#by#p# delete sp; delete[]#p#frees#the#array#beginning#at#p# delete[] stk; new#uses#t's#constructor#for#objects#of#type#t# need#a#default#constructor#for#array#alloca@on# delete#uses#t's#destructor#~t()# use#new/delete#instead#of#malloc/free#and#never#mix#new/delete# and#malloc/free# Controlled#pointers# References# When#you#need#a#way#to#access#an#object,#not#a#copy#of#it# In#C,#we#used#pointers# int var = 3; int *pvar = &var; *pvar = 5; // now var == 5 In#C++,#references#acach#a#name#to#an#object# int var = 3; int &rvar = var; rvar = 5; // now var == 5 Unlike#pointers,#you#can t#define#a#reference#without#an#object#it# refers#to# int &x; (X)# CallRbyRReference# CallRbyRreference#allows#you#to#modify# arguments# Now#you#can#implement#swap()#func@on#using# callrbyrreference# void swap(int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; swap (&a, &b); void swap(int &x, int &y) { int temp; temp = x; x = y; y = temp; // pointers are implicit swap(a, b); CallRbyRValue#/#CallRbyRReference# CallRbyRvalue# By#default,#C/C++ s#uses#callrbyrvalue# If#you#pass#an#object#using#callRbyRvalue,#it#causes#the#object#to#copy,# which#is#inefficient#if#it#is#large# CallRbyRreference# In#effect,#you#just#pass#the#address#of#an#object# CallRbyRconstRreference#addi@onally#guarantees#that#the#object#will#not# be#modified#during#the#call# Java#func@on#call#is#similar#to#callRbyRreference# Java#actually#passes#pointers#internally# // call-by-reference void foo(stack &s) { Stack s; foo(s); // s can be modified in foo // call-by-const-reference void foo(const Stack &s) { Stack s; foo(s); // s is guaranteed to stay the same

Constness# Don t# miss# ; # C++#Classes# from#[1]# Way#to#say#something#is#not#modifiable# char greeting[] = "Hello"; char *p = greeting; // non-const pointer, non-const data const char *p = greeting; // non-const pointer, const data char * const p = greeting; // const pointer, non-const data const char * const p = greeting; // const pointer, const data // Objects a references or b points to cannot be modified in this function void foo(const Stack &a, const Stack *b); // For class member member method // This does not modify any status of this object void Stack::size() const; from#[3]# class Thing { methods and variables accessible from all classes protected: methods and variables accessible from this class and child classes methods and variables only visible to this class defines#a#data#type#'thing # can#declare#variables#and#arrays#of#this#type,#create#pointers#to# them,#pass#them#to#func@ons,#return#them,#etc.# Object:#an#instance#of#a#class#variable# Method:#a#func@on#defined#within#the#class# // simple-minded stack class class Stack { Stack(); // constructor decl int push(int); int pop(); // default visibility int stk[100]; int *sp; Stack#Class#in#C++# Stack::Stack() { // constructor implementation sp = stk; int stack::push(int n) { return *sp++ = n; int stack::pop() { return *--sp; Stack s1, s2; // calls constructors s1.push(1); // method calls s2.push(s1.pop()); from#[1]# Constructors# Student(const string &n, double gpa) { name = n; this->gpa = gpa; // when a member variable name and a parameter name are the same string name; double gpa; Creates#a#new#object# Construc@on#includes#ini@aliza@on,#so#in#may#be#parameterized#like#other# methods# You#can#have#mul@ple#constructors#with#different#parameters# If#you#don t#define#any#constructors,#a#default#constructor#will#be# generated# Student() { this #is#a#pointer# #so#you#need# R> #to#refer#to#it#

Constructors# explicit #Keyword# class MyClass { MyClass(int arg) { MyClass(int arg1, arg2) { // These call constructor and create objects on the stack MyClass m1(100); MyClass m2 = 100; MyClass m3(100, 300); // These call constructor and create objects on the heap MyClass *m4 = new MyClass(100); MyClass *m5 = new MyClass(100, 300); // You can omit () when you call the default constructor (if there is one) MyClass m6; // equivalent to MyClass m6(); MyClass *m7 = new MyClass; // equivalent to MyClass *m7 = new MyClass(); Compiler#does#automa@c#typeRconversion#for#oneRargument# constructors# When#this#is#a#constructor:# MyClass(int arg); This#creates#a#temporary#object#and#assigns#it#to#m# MyClass m = 5; It#is#some@mes#not#what#we#want;#to#prevent#this,#use# explicit # keyword# explicit MyClass(int arg); // When this can be desirable class string { string(const char *s); string str = Hello world ; // Good! // When this is not desirable class vector { vector(int size); vector v = 5; // Oh no! Use explicit Inline#Func@ons# Accessors#vs.#Mutators# Inlined#func@ons#are#copied#into#callers #body#when#compiled# Can#prevent#func@on#call#overhead# Can#increase#code#size# inline #direc@ve#suggests#the#func@on#is#to#be#inlined# So#inline#func@ons#should#be#available#at#compile#@me#(not#link#@me)# # they#should#exist#in#the#same#source#file#or#any#other#header#files# included# But#the#final#inlining#decision#is#on#compiler# Member#func@ons#defined#within#a#class#have#the#same#effect# Mutators#can#alter#the#state#(=#nonRsta@c# member#variables)#of#an#object,#while# accessors#cannot# Accessors#have# const #at#the#end#of#the# signature# void setgpa(double gpa) { this->gpa = gpa; # void setgpa(double gpa); inline void setgpa(double gpa) { this->gpa = gpa; Two#are# Same!# void setgpa(double gpa) { this->gpa = gpa; // mutator double getgpa() const { return gpa; // accessor

// This calls default constructor for string // first and then assigns new string n to // it again Student(const string &n, double gpa) { name = n; this->gpa = gpa; string name; double gpa; # Ini@alizer#Lists# // This calls constructor for string only // once Student(const string &n, double gpa) : name(n), gpa(gpa) { string name; double gpa; Ini@aliza@on#lists#are#more#efficient# Only#call#constructors#once# Difference#is#small#for#primi@ve#data#types# You#have#to#use#ini@alizer#lists#for#some#variables# Class#objects#that#do#not#have#default#(=#no#argument)#constructors# Reference#variables# They#cannot#be#created#without#the#target#they#refer#to# Default#Parameters# Specifies#default#values#for#func@on# parameters# Included#in#the#func@on#declara@on# void printint(int n, int base=10); printint(50); // equivalent to printint(5, 10);, outputs 50 printint(50, 8); // outputs 62 (50 in octal) The#Big#Three# Copy#Constructor# MyClass(const MyClass &rhs) Special#constructor#to#construct#a#new#object#as#a#copy#of#the#same#type#of#object# operator=# operator=(const MyClass &rhs) Copy#assignment#operator# Applied#to#two#already#constructed#objects# Destructor# ~MyClass() Destroys#an#exis@ng#object# If#you#have#some#member#variables#that#are# new ed,#you#should#delete#them#here# Called#when# An#object#on#the#stack#goes#out#of#scope#()# An#object#on#the#heap#is#deleted#using# delete # If#you#don t#write#these#by#yourself,#default#ones#will#be#generated#by#compiler# Write#these#only#if#you#want#to#do#some#addi@onal#tasks# The#Big#Three# // Normal constructor Student(const string &name, double gpa) : name(name), gpa(gpa) { someobj = new MyClass(); // Copy constructor Student(const Student &rhs) : name(rhs.name), gpa(rhs.gpa) { someobj = new MyClass(); // Destructor ~Student() { delete someobj; // operator= operator=(const Student &rhs) { name = rhs.name; gpa = rhs.gpa; someobj = MyClass(rhs.someObj); // Calls copy constructor of MyClass string name; double gpa; MyClass *someobj;

void somefunction() { The#Big#Three# // Calls the normal constructor Student jane( Jane, 3.0); // stack Student *pjane = new Student( Jane, 3.0); // heap // Calls the copy constructor Student tom(jane); // stack student *ptom = new Student(jane); // heap // Calls the operator=() tom = jane; *ptom = *pjane; // Calls the destructor for heap objects delete pjane; delete ptom; // At this point the destructor for stack objects (jane and tom) are called Friends# Way#to#grant#private#member#access#to#specific# classes/func@ons# class ListNode { int element; ListNode *next; ListNode(int element, ListNode *next=null) : element(element), next(next) { friend class List; // friend class friend int somefunction(); // friend methods class List { List() { head = new ListNode(); // can call ListNode s private constructor ListNode *head; int somefunction() { The#struct#Type# A#class#in#which#the#members#default#to#public# In#a#class,#the#members#default#to#private# Unlike#C,#you#don t#need#a# struct #keyword#to# refer#to#a#struct#type,#because#it#is#now#a# class # struct MyClass { MyClass(int arg) { Namespaces# C++#equivalent#of#Java#packages# namespace myspace { class Professor { // Refers to student class with the namespace name myspace::student s; myspace::professor p; // This allows you to use Student without the namespace name using myspace::student; Student s; myspace::professor p; MyClass m(100); // This allows you to use everything in myspace without the namespace name using myspace; Student s; Professor p;

Incomplete#Class#Declara@on# Unlike#Java,#the#order#of#class#declara@on#macers# If#class#B#is#declared#aver#class#A,#class#A#does#not# know#about#class#b# But#some@mes#class#A#needs#to#know#(at#least)#the# existence#of#class#b# ex)#a#has#b s#pointer#as#a#member#and#b#has#a s#pointer#too# Solu@on:#incomplete#class#declara@on# We#can#incompletely#declare#class#B#before#class#A# The#only#thing#class#A#knows#about#B#is#its#existence;#A# does#not#know#about#b s#members#or#b s#object#size# because#b s#full#declara@on#is#below#a# Incomplete#Class#Declara@on# class B; // incomplete class declaration class A { // Now A knows B s existence void foo1(b *b); // OK void foo2(b &b); // OK void foo3(b b); // (X) Not OK! A does not know B s object size void bar(b *b) { b->baz(); // (X) Not OK! A does not know about B s members B *data1; // OK B &data2; // OK B data3; // (X) Not OK! A does not know B s object size class B { void baz() { A *data; Inheritance# Inheritance# Basic#syntax# class Child : public Parent { Actually#there#are#also#private#and#protected#inheritance# # nevermind,#you#are#not#going#to#use#them.#just#don t# forget#to#use# public #keyword# Calling#base#class#constructor#in#ini@alizer#lists# Child(int arg1, int arg2) : Parent(arg1), { Calling#base#class#func@ons# Parent::foo(); class Person { Person(int ssn, const string &name) : ssn(ssn), name(name) { const string &getname() const { return name; int getssn() const { return ssn; void print() const { cout << ssn <<, << name int ssn; string name; class Student : public Person { Student(int ssn, const string &name, double gpa) : Person(ssn, name), gpa(gpa) { double getgpa() const { return gpa; void print() const { Person::print(); cout <<, << gpa; // override double gpa;

Dynamic#Dispatch# Java#always#uses#the#run@me#type#to#decide# which#method#to#use# But#C++#uses#the#sta@c#type#by#default# Student s(123456789, Jane, 4.0); s.print(); // calls Student::print Virtual#Func@ons# You#need#a# virtual #keyword#to#tell#the#compiler#this# func@on#should#use#dynamic#dispatch# In#Java,#all#func@ons#are#virtual#func@ons# class Person { virtual void print() const { cout << ssn <<, << name Person &p1 = s; p1.print(); Person *p2 = &s; p2->print(); // p1 and s are same object // calls Person::print! // p2 points to s // calls Person::print! class Student : public Person { This#can#be#omiced#in# child#class# virtual void print() const { Person::print(); cout <<, << gpa; The#Big#Three#Revisited# Virtual#Destructor# In#a#subclass,#the#default#Big#Three#are#constructed#if#you#don t# explicitly#define#them# Copy#constructor# Invokes#copy#constructor#on#the#base#class(es)# And#then#invokes#copy#constructors#on#each#of#newly#added#members# operator=# Invokes#operator=#on#the#base#class(es)# And#then#invokes#operator=#on#each#of#newly#added#members# Destructor# Invokes#destructors#on#each#of#newly#added#members# And#then#invokes#destructor#on#the#base#class(es)# In#a#base#class,#the#destructor#should#be#declared#virtual# Otherwise#the#base#class#por@on#of#the#object#will#not#be# deleted#if#it#is#deleted#through#base#class#pointer/reference# class Person { virtual ~Person() { Student *tom = new Student( 123456, Tom, 3.0); Person *p = tom; // If ~Person() is declared non-virtual, this will not delete the base class portion of the object delete p;

Abstract#Methods#and#Classes# C++#equivalent#of#Java#abstract#methods#and#classes# Abstract#classes#cannot#be#instan@ated# In#C++,#a#method#is#abstract#if:# It#is#declared#virtual# The#declara@on#is#followed#by#=0# ex)#virtual double area() const = 0; In#C++,#a#class#is#abstract#if:# It#has#at#least#one#abstract#method# Slicing# You#can#access#child#classes#by# pointers#and#references#of# base#classes# But#you#can t#use#base#classes# objects#to#access#child#classes# Student jane(12345, Jane, 4.0); Person p(54321, Bob ); p = jane; // object is sliced! p.print(); Jane # 12345# 4.0# Student jane; void print(person p) { p.print(); print(jane); // call-by-value, so object is sliced! Jane # 12345# GPA#is# sliced# off## Person p = jane; Type#Conversions# Type#Conversions# C++Rstyle#casts# sta@c_cast# Similar#to#CRstyle#cast# dynamic_cast# Can#only#be#used#with#pointers#and#references#to#classes#(or#with#void*)# Performs#a#run@me#check#if#the#cast#is#correct;#returns#NULL#if#incorrect# const_cast# Manipulates#the#constness#of#the#object#pointed#by#a#pointer,#either#to#be#set# or#to#be#removed# reinterpret_cast# Converts#any#pointer#type#to#any#other#pointer#type# Simple#binary#copy#of#the#value#from#one#pointer#to#the#other# LLVMRstyle#casts# cast,#dyn_cast,#cast_or_null,#dyn_cast_or_null# class Base { class Derived: public Base { Base *pb = new Base; // C-style cast Derived *pd = (Derived*) pb; // static_cast Derived *pd = static_cast<derived*>(pb); // dynamic_cast Derived *pd = dynamic_cast<derived*>(pb); // returns NULL if failed if (!pd) cout << Type casting failed! ; // const_cast void printstr (char *str) { cout << str << '\n'; const char *c = Hello world"; printstr(const_cast<char*>(c)); // removes constness to pass it to printstr

Mul@ple#Inheritance# Don t#use#this#unless#you#really#need#to# Has#many#tricky#aspects# You#don t#need#to#use#this#in#your#code#in#cos320# We#are#not#going#to#cover#the#details#here# class Person : public Printable, public Serializable { class Student : virtual public Person { class Employee : virtual public Person { class StudentEmployee : public Student, public Employee { References# [1]#Brian#Kernighan,#COS333#lecture#notes,# 2013.# [2]#Mark#Allen#Weiss,#C++#for#Java# Programmers,#Pearson#Pren@ce#Hall,#2004.# [3]#Scoc#Meyers,#Effec@ve#C++#Third#Edi@on,# AddisonRWesley,#2005.#