0% found this document useful (0 votes)
59 views

UCP 2015s2 Lecture10 C++

Unix and C programming and C++

Uploaded by

bat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views

UCP 2015s2 Lecture10 C++

Unix and C programming and C++

Uploaded by

bat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

UNIX and C Programming (COMP1000)

Lecture 10: C++

Updated: 29th July, 2015

Department of Computing
Curtin University

Copyright © 2015, Curtin University


CRICOS Provide Code: 00301J

1/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Textbook Reading (Hanly and Koffman)

For more information, see the weekly reading list on Blackboard.


I Chapter 15: On to C++
I C++ is introduced very briefly by Hanly and Koffman.
I For more information, look for a dedicated C++ book.
I e.g. Thinking in C++, by Bruce Eckel (freely available).

2/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Outline
C++ Overview

Scope

Classes

Inheritance

Input and Output

Pointers

Templates

Overloading

3/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

C++ Overview

I This lecture will briefly introduce C++ from a Java(ish)


perspective.
I However, C++ is much older than Java.
I C and C++ co-evolved.
I C++ is much more complex than C.

4/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Commonalities with C

I C++ uses header files in the same way as C.


I C++ uses the C preprocessor (#include, etc.).
I C++ has the same primitive data types as C (int, float,
etc., but also has a “bool” data type).
I C++ has the same basic control structures as C (if, switch,
for, while and do-while).
I The main() function works the same way in C++ as in C.
I Like C, C++ lacks garbage collection.

5/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Major Differences with C

I C++ has classes, with inheritance and polymorphism.


I C++ uses “new” and “delete” instead of “malloc()” and
“free()”
I C++ has namespaces and a different set of libraries.
I C++ has exception handling (try-catch).
I C++ has operator overloading (which can radically alter the
language!)

6/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Filename Extensions

I The typical filename extensions are:


I “.cpp” for a C++ source file.
I “.hpp” for a C++ header file.
I The standard C++ header files don’t have extensions:
#include <iostream>

7/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Compiling
I Gcc can compile C++ as well as C:
[user@pc]$ gcc -c file1.cpp

[user@pc]$ gcc -c file2.cpp

[user@pc]$ gcc file1.o file2.o -o prog -lstdc++


I The “.cpp” extension tells gcc that it’s dealing with C++ code.
I Other normal gcc options are supported as usual.
I “-lstdc++” tells gcc to link against the C++ library
I Alternatively, you can use “g++”:
[user@pc]$ g++ file1.o file2.o -o prog
I Makefiles are used for C++, just as for C.

8/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Namespaces

I A “namespace” is similar to a “package” in Java.


I Standard C++ functions and classes are generally in “std”.
I Thus, you often have this right after your “#include”s:
using namespace std;

I Without this, you would have to prepend “std::” to a lot of


things.

9/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Scope Resolution Operator — “::”


I The “::” operator is used to refer to something inside a
namespace or class (but not an object!)
I For instance, to call a static method:
c = ClassName::methodName(a, b);

I Also (if you don’t have “using namespace std;”):


std::string str = "Hello world";

I However, to call a non-static method:


obj.methodName();
ptr->methodName();

I “.” and “->” mean the same thing as in C.


I You may (or may not) have a pointer to the object.

10/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Classes

I Classes in C++ are an extension to structs in C.


I They have methods (a.k.a. “member functions”).
I They have public, private and protected fields and member
functions.
I Conventionally:
I The class and its members are declared in a header file.
I Each member function is defined in the main source file.

11/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Class Syntax
This would appear in “person.hpp”:
class Person {
public:
Person(); // Constructor
Person(string inName, int inAge);
~Person(); // Destructor

int getAge() const; // Accessor


void setAge(int inAge); // Mutator
... // Other methods

private:
string name; // Private fields
int age;
};
12/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Member Function Definitions


This would appear in “person.cpp”:
Person::Person(string inName, int inAge) {
name = inName;
age = inAge;
}

int Person::getAge() const {


return age;
}

... // Other methods

I Note the use of “Person::” before each member.


I Note the “const” after getAge() — this means the method
does not modify the object.
13/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Creating and Destroying Objects


I In C++, the “new” keyword replaces malloc():
Person* p;
p = new Person("Ralph", 7);
I Allocates memory for a Person object.
I Calls the constructor to initialise it.
I We can then manipulate the object as follows:
int a = p->getAge();
p->setAge(a + 1);
I Also, “delete” replaces free():
delete p;
I Calls the destructor to clean up.
I De-allocates the memory.
14/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Creating and Destroying Arrays

I The “new” keyword can also allocate arrays:


int* array;
array = new int[100];

I Such arrays must eventually be de-allocated with “delete[]”


(not “delete”):
delete[] array;

15/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Stack-Based Objects
We can also allocate objects on the stack:
void func() {
Person p("Ralph", 7); // Constructs p
...
int age = p.getAge();
p.setAge(age + 1);
...
}

I Declares a Person object on the stack (without “new”).


I The constructor is called immediately.
I The destructor is called automatically at the end of the
function.
I You use “.” to access fields and methods (no dereferencing).
I You can’t do this in Java!
16/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Destructors

I A destructor is the inverse of a constructor.


I With no garbage collection, C++ relies on destructors to clean
up.
I There is only one destructor per class.
I It takes no parameters and returns nothing.
I Its role is to free resources (particularly memory) used by the
object, before the object itself is removed from memory.

17/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Static Methods
I C++ supports static fields and methods.
I A static field/method is shared by all instances of the class.
I This is same meaning as in Java (not C!)
I For example:
class Person {
public:
...
static void staticFunc(int param);
...
};
...
Person::staticFunc(10);

18/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Member Access Operators


I C++ has 3 operators for accessing members of objects, classes
and namespaces: “.”, “->” and “::”.
I You need each one in different circumstances:
Operator Example Used when. . .
. obj.method() obj is an object.
-> ptr->method() ptr is a pointer to an object.
:: cls::method() cls is a class or namespace.

A Note on Java
I Java has no equivalent to the “.” operator in C/C++
(because you can’t have an object without a reference).
I Confusingly, Java uses the symbol “.” to replace “->” and
“::”.
19/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

The this Pointer

I As in Java, “this” is a pointer to the current object.


I Can be used to distinguish between fields and local variables or
parameters.
I We could write our Person constructor as follows:
Person::Person(string name, int age) {
this->name = name;
this->age = age;
}

20/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Inheritance
Classes can inherit/extend other classes, as follows:
class Employee : public Person {
public:
Employee();
Employee(string name, int age, int salary);
~Employee();
...
};
However:
I Classes don’t have to inherit from anything (unlike in Java).
I C++ supports multiple inheritance (use sparingly, if at all):

class SubClass : public SuperClassA,


public SuperClassB {
...
21/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Virtual Methods
In C++, you can’t override a method unless it’s “virtual”:
class Person {
...
virtual bool equals(Person* p) const;
...
};

class Employee : public Person {


...
virtual bool equals(Employee* e) const;
...
};

I Employee::equals() overrides Person::equals().


I In Java, all methods are implicitly virtual.
22/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Calling a Superclass Method


We need to call Person::equals() inside Employee::equals()
I In Java, we would do this:
if(super.equals(var) && ...) { // Java
Java keyword
I However, C++ has no “super” keyword.
I Instead, you refer to the superclass’s name:
if(Person::equals(var) && ...) { // C++
superclass name
(This looks like a static method call, but C++ is smart
enough to know otherwise.)

23/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Calling a Superclass Constructor


I We also need to call Person’s constructor from within
Employee’s constructor.
I C++ has a different syntax for this:

Employee::Employee(string inName, int inAge,


int inSalary) : Person(inName, inAge)
{
salary = inSalary;
}

I The super-constructor call is highlighted.


I Person’s constructor is called like a function, but before the
first brace (and after a colon).

24/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Pure Virtual (Abstract) Methods

I A virtual function is “pure” if it has no definition.


I A “pure” virtual function must be overridden.
I This is equivalent to an abstract method in Java (but there’s
no “abstract” keyword).
I An abstract class is any class containing a pure virtual
function.

class Person { // Abstract class


...
virtual float calcTax() = 0; // Pure virtual
...
};

25/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Input and Output


C++ has a radically different syntax for I/O operations:
#include <iostream>
using namespace std;

int main() {
int num1, num2;

cout << "Enter two integers: ";


cin >> num1 >> num2;

cout << "Sum: " << (num1 + num2) << endl;


return 0;
}

I cin and cout are objects defined in the standard “iostream”


library.
26/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Reading and Writing Files

I The fstream library defines classes for reading and writing


files.
I ifstream — an input file stream.
I ofstream — an output file stream.
I The constructor of ifstream/ofstream opens a given file.
I The destructor closes it.
I Read using the » operator (like cin).
I Write using the « operator (like cout).

27/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Writing Files — Example


Write the integers 1–100 to file.txt:
#include <fstream>

int main() {
ofstream* file = new ofstream("file.txt");

for(int i = 0; i < 100; i++) {


*file << i << endl;
}

delete file;
return 0;
}

28/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Writing Files — Alternative Example


Alternatively:
#include <fstream>

int main() {
ofstream file("file.txt"); // Stack-based object

for(int i = 0; i < 100; i++) {


file << i << endl;
}

return 0;
}

I Now, file is an object on the stack — no pointers.


I The destructor is called automatically at the function’s end.
29/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

References
I A C++ “reference” is a pointer that is automatically
dereferenced.
I When used, C++ automatically puts a * in front of it.
I References are set once (when declared). You can’t change
where they point.

int x = 10;
int& y = x; // y is a reference to integer x.

y = 20; // Sets x to 20.

I Here, y is a reference to x.
I The & in the declaration means “reference-to”, not “address-of”.
I But what’s the point?

30/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Reference Parameters
I Functions (and methods) can take references as parameters:
void swap(int& a, int& b) {
int temp = a;
a = b;
b = temp;
}

...
int x = 10, y = 20;
swap(x, y);

I Be careful here — it’s not obvious that x and y are being


passed by reference!

31/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Auto Pointers
I “Auto pointers” are another special type of pointer.
I Only one auto pointer can point to a given object!
I If you try to copy the pointer, the original pointer will be
wiped.
I Auto pointers are implemented by the class “auto_ptr”.
#include <memory>
...
auto_ptr<Employee> ptr(new Employee());

This declares an auto pointer called “ptr”, pointing to a new


Employee object.
I When ptr disappears, the Employee object will be
automatically deleted.

32/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

More Smart Pointers

I Auto pointers are one example of “smart” pointers.


I Smart pointers are special objects that represent pointers and
make them safer or more convenient.
I The Boost library (not quite part of C++) defines several
different types.
I Some are designed for arrays.
I Some are designed to allow multiple pointers to a single object.
I Auto pointers have now been deprecated in standard C++ by
“unique pointers”.

33/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Templates

I Templates in C++ are similar to Java’s generics (but the


underlying implementation is very different).
I Templates let you write generic code that can handle any data
type.
I This is especially useful for containers.
I Much of the C++ API uses templates (e.g. auto pointers).
I Both template functions and template classes are possible.

34/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Template Declarations

I A template (function/class) begins with this line:


template <class A, class B, class C>

I This is followed by a normal(ish) function or class definition.


I The first line provides the “template parameters”: A, B and C.
I These can be used within the function/class as ordinary data
types.

35/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Template Functions
A template function might look like this:
template<class T>
T square(T num) {
return num * num;
}

Here, square() is a template function:


I When called with an int, it will return an int.
I When called with a float, it will return a float.
I For each data type you use, the compiler generates a separate
copy of the function.
I When called with something that can’t be multiplied, the
compiler will output an error.

36/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Template Classes (1)


A template class might look like this:
template<class T>
class Secret {
public:
Secret(T inObj, string inPassword);
~Secret();
T getObj(string inPassword);

private:
T obj;
string password;
};

I The “Secret” template class stores an arbitrary piece of data.


I The class itself doesn’t care what the type is.
37/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Template Classes (2)


We can instantiate the “Secret” template class as follows:
Secret<int> *s1 = new Secret<int>(5, "pass");
Secret<string> *s2 =
new Secret<string>("spaceballs", "12345");

int a = s1->getObj("pass");
string b = s2->getObj("12345");

I This creates two objects, pointed to by s1 and s2.


I It also creates two versions of the class — one for ints and
one for strings.
I The getObj() method returns the appropriate type.

38/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Templates vs. Generics

I C++’s templates and Java’s generics are not quite the same.
I Templates work by creating different copies for different types.
I Generics work by automatically inserting safe typecasts.
I They have similarities:
I Both let you re-use code for different data types.
I Both let you avoid gratuitous, unsafe typecasting.
I And differences:
I Templates apply to any data type; generics apply only to
objects.
I Templates allow compile-time calculations
(“metaprogramming”).

39/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

The Standard Template Library (STL)


I C++ provides a number of standard template classes.
I These implement most commonly-needed abstract data types:
lists, sets, maps, stacks, queues, iterators, etc.
I For example, vector is a resizeable list:
vector<int> vec; // A vectors of ints

for(int i = 0; i < 10; i++) {


vec.push_back(i);
}

for(int i = 0; i < 10; i++) {


cout << vec[i] << endl;
}

40/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Method/Function Overloading
I C++ allows for function and method overloading (like Java,
but unlike C).
I Multiple functions/methods can have the same name, but
different parameter lists.
I For example:
int readInt() {
...
}

int readInt(string prompt) {


...
}

The compiler will determine which method to call based on the


parameters.
41/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Default Arguments
I C++ lets you set “default” values for function parameters:
int readInt(string prompt = "Enter a value: ") {
...
}

You can call this function with or without a parameter:


int x = readInt();
int y = readInt("Enter y: ");

When no parameter is given, the default is used.


I You can do this for several parameters:
void func(int w, float x = 1.0, int y = 2) {...}

I Default arguments must come last in the parameter list.


42/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Operator Overloading (1)


I In C++, it is possible to define different meanings for
operators (+, *, ==, &&, ->, [], etc.).
I Instead of an equals() method for the Person class, we could
define the == operator:
class Person {
public:
...
bool operator==(const Person& other) const;
...
};

I Here, we effectively have a method with the name


“operator==”.
I This will be called when you write “person1 == person2” (if
person1 and person2 are both Person objects).
43/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Operator Overloading (2)

I The applications of operator overloading are endless.


I It’s how the « and » operators work with cin and cout.
I It’s also heavily used by auto pointers and vectors.
I There are very few limits to what you can do.
I Use with care! (Gratuitous operator overloading makes your
code extremely unreadable.)

44/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

Wrapping Up

I This has just been a taste of C++.


I There are still more features and many more nuances.
I There are also many other languages that follow in the
footsteps of C.
I Some of these include: Objective C, Java, C#, D and Go.
I Sadly, this will not be in the exam!

45/46
C++ Overview Scope Classes Inheritance Input and Output Pointers Templates Overloading

That’s all from UCP

I Hopefully you’ve understood most of it!


I Make sure you finish all the pracs.
I Good luck!

46/46

You might also like