SlideShare a Scribd company logo
1 of 107
DATA STRUCTURES &
ALGORITHMS
C++ WARM-UP
- PREM RANJAN
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructor, copy constructor, and assignment operator
• Const
• Template
HISTORY OF C++
• 1972: C language developed at Bell Labs
• Dennis Ritchie wrote C for Unix OS
• Needed C for work with Unix
• late 70s: C becomes popular for OS development by many vendors
• Many variants of the language developed
• ANSI standard C in 1987-89
HISTORY OF C++ (CONTINUED)
• early 80s: Bjarne Stroustrup adds OO features to C creating C++
• 90s: continued evolution of the language and its applications
• preferred language for OS and low level programming
• popular language for application development
• low level control and high level power
CONCEPTUALLY WHAT IS C++
• Alternatives:
• is it C, with lots more options and features?
• is it an OO programming language with C as its core?
• is it a development environment?
• On most systems it is a development environment, language, and library,
used for both procedural and object oriented programming, that can be
customized and extended as desired
VERSIONS OF C++
• ANSI C++
• Microsoft C++ (MS Visual C++ 6.0)
• Other vendors: Borland, Symantec, Turbo, …
• Many older versions (almost annual) including different version of C too
• Many vendor specific versions
• Many platform specific versions
• For this class: Unix / Linux based versions
• g++
CHARACTERISTICS OF C++ AS A COMPUTER
LANGUAGE
• Procedural
• Object Oriented
• Extensible
• ...
OTHER OO LANGUAGES
• Smalltalk
• pure OO language developed at PARC
• Java
• built on C/C++
• objects and data types
• Eifel and others
WHAT YOU CAN DO WITH C++
• Apps (standalone, Web apps, components)
• Active desktop (Dynamic HTML, incl Web)
• Create graphical apps
• Data access (e-mail, files, ODBC)
• Integrate components w/ other languages
DISADVANTAGES OF C++
• Tends to be one of the less portable languages
• Complicated?
• 40 operators, intricate precedence, pointers, etc.
• can control everything
• many exceptions and special cases
• tremendous libraries both standard, vendor specific, and available for
purchase, but all are intricate
• Aspects above can result in high maintenance costs
ADVANTAGES OF C++
• Available on most machines
• Can get good performance
• Can get small size
• Can manage memory effectively
• Can control everything
• Good supply of programmers
• Suitable for almost any type of program (from systems programs to
applications)
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructore, copy constructor, and assignment operator
• Const
• Template
PRIMITIVE TYPES
• bool true or false (only C++)
• char 8/16-bit
• short 16-bit signed integer
• int 32-bit signed integer
• unsigned 32-bit unsigned integer
• long 32 / 64-bit signed integer
• float 32-bit floating point
• double 64-bit floating point
OPERATORS AND PRECEDENCE
• [ ] .
• to access arrays elements / to access object methods and fields
• expr++ expr-- ++expr --expr !
• new (type)expr
• * / %
• + -
• << >> (integers only)
• < > >= <=
• == !=
• &
OPERATORS AND PRECEDENCE
• ^
• |
• && (booleans only)
• || (booleans only)
• ?:
• = += -= *= ….
• C++ allows operator overloading
PRECEDENCE EXAMPLE
• What is: 5 + 21 / 4 % 3
• = 5 + (21 / 4) % 3
• = 5 + ( 5 % 3)
• = 5 + 2
• = 7
EXPLICIT CASTING
• (type) expression
• Possible among all integer and float types
• Possible among some class references
• E.g. int i = (int) ( (double)5 / (double)3 )
IMPLICIT CASTING
• Applied automatically provided there is no loss of precision
• float  double
• int  double
• Example
• int iresult, i=3;
• double dresult, d=3.2;
• dresult = i/d => implicit casting dresult=0.9375
• iresult = i/d => error! Why? Loss in precision, needs explicit casting
CONTROL FLOW
if (boolean)
statement;
else if(boolean)
statement2;
else
statement3;
Booleans only, not integers!
• if (i > 0)  correct
• if (i = 2)  correct / incorrect ?
SWITCH / CASE
• switch (controlVar)
{
case 'a' :
statement-1
break;
case 'b' :
statement-2
break;
default :
statement-3
break;
}
• Do not forget the break command to avoid surprise result!
LOOPS
while(<boolean>)
statement;
do
statement;
while(<boolean>)
for(init-expr; <boolean>; incr-expr)
statement;
SOME CONVENTIONS FOR VARIABLE NAMES
• Use letters and numbers
• Do not use special characters including spaces, dots, underlines, pound signs,
etc.
• The first letter will be lower case
• Use variable names that are meaningful (except for occasional counters that
we might call i, j, x, etc.)
• You can concatenate words, and capitalize each after the first, e.g., bankBal,
thisAcctNum, totAmt
• If you abbreviate, be consistent. For example do not use both bankBal and
totalBalance as variable names.
SOME CONVENTIONS FOR STRUCT AND CLASS NAMES
• In creating names of structs and classes, apply the same rules
as for variable names, except the first character will be upper
case
• Example:
• an object's name: myCar
• the struct or class name: Car
• Another Example: aPerson and Person
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructore, copy constructor, and assignment operator
• Const
• Template
PASSING PARAMETERS
• C++ allows for three different ways of passing parameters:
• Pass “by value”
• E.g. foo (int n)
• Appropriate for small objects (usually primitive types) that should
not be altered by the function call
• Pass “by constant reference”
• E.g. foo(const T& myT)
• Appropriate for large objects that should not be altered by the
function call
• Pass “by reference”
• E.g. foo(bool & errFlag)
• Appropriate for small objects that can be altered by the function call
• Array types are always passed “by reference”
PASSING BY VALUE
void square(int i)
{
i = i*i;
}
int main()
{
int i = 5;
square(i);
cout << i << endl;
}
PASSING BY REFERENCE
void square(int& i)
{
i = i*i;
}
int main()
{
int i = 5;
square(i);
cout << i << endl;
}
PASSING BY CONSTANT REFERENCE
void square(const int& i)
{
i = i*i;
}
int main()
{
int i = 5;
square(i);
cout << i << endl;
}
Wont work, why?
PASSING BY CONSTANT REFERENCE
int square(const int& i)
{
return i*i;
}
int main()
{
int i = 5;
cout << square(i) << endl;
}
Will it his work?
WHAT IS A REFERENCE?
• An alias – another name for an object.
int x = 5;
int &y = x; // y is a reference to x
y = 10;
• What happened to x?
• What happened to y? – y is x.
WHY ARE THEY USEFUL?
• When passing argument of large size (class type), can save space
• Sometimes need to change a value of an argument
• Can be used to return more than one value (pass multiple parameters by
reference)
HOW ARE REFERENCES
DIFFERENT FROM POINTERS?
Reference Pointer
int a = 10;
int b = 20;
int &c = a;
c = b;
What is the value of a?
int a = 10;
int b = 20;
int *c = &a;
c = &b;
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructore, copy constructor, and assignment operator
• Const
• Template
CLASSES
• Provide a mechanism for defining classes of objects.
• We can define the class of all computers to have certain
characteristics.
• An instance of a computer is your home PC.
• Classes contain member variables and member
functions.
CLASSES IN C++:
WHY CREATE CLASSES / OBJECTS?
• Keeps all related info (i.e., data) together
• Refer to all the related info by one name
• Protect the information
• Hide methods that use or change the info
• Keep methods together with their related info
EXAMPLE OF BENEFITS OF CREATING AN OBJECT
• Keeps all related info (i.e., data) together
Person thisPerson;
Person thisPerson = new Person ("Bill", "Clinton", 52);
• Refer to all the related info by one name
thisPerson
• Protect the information
lastName = "Dole"; //normally data members
are private, and member functions are public
CLASSES AND OBJECTS
Mammals
Humans Tigers
Hank Peggy Tony
class
class
class
inherits inherits
instance-ofinstance-of
EXAMPLE OF A SIMPLE CLASS
class Change
{
private:
int quarters;
int dimes;
public:
int getQuarters() {return quarters;}
int getDimes() {return dimes;}
void setQuarters(int aQuarters) {quarters = aQuarters;}
…...
void printChange()
{cout << "nQuarters: " << quarters
<< " Dimes: " << dimes << endl;
}
};
MORE CLASS EXAMPLE
class human
{
// this data is private to instances of the class
int height;
char name[];
int weight;
public:
void setHeight(int heightValue);
int getHeight();
};
FUNCTION DEFINITIONS
void human::setHeight(int heightValue)
{
if (heightValue > 0)
height = heightValue;
else
height = 0;
}
int human::getHeight()
{
return(height);
}
EXAMPLE
// first we define the variables.
int height = 72;
int result = 0;
human hank;
//set our human’s height
hank.setHeight(height);
//get his height
result = hank.getHeight();
cout << “Hank is = “ << result <<
“inches tall” << endl;
Hank is 72 inches tall
Output
INSTANTIATING AN OBJECT
• The class definition does not create any objects
• Instantiating and constructing are equivalent words for building a
new object based on the model (i.e., template) of the class
• Instantiating is done just like declaring a variable of a built in data
type
• Instantiating is done by a constructor (sometimes called a
constructor method)
• If the "class provider" does not provide a constructor, then the C++ compiler
provides a default one automatically
• The default constructor does not provide values to the data members (i.e. the
instance variables)
INSTANTIATING AN OBJECT (MORE)
• When the object is instantiated, memory is allocated
• Example of instantiation (implicit call of constructor)
Car myCar;
Elephant oneElephant, twoElephant;
• No initialization takes place
• Each object has its own memory allocation
• oneElephant and twoElephant are separate objects in different locations in memory
• Each is addressed individually by name or location
• Each data member is addressed individually using the object name and the data
member name, for example:
oneElephant.age
twoElephant.name
REFERENCING AN OBJECT
• Each object has a name (or a location) which is assigned when the object is
instantiated
• private data members are accessible only within the class
• since most data members are private, that means that these data items are accessed
generally by means of member functions
• myElephant.age = 72; //won't work, assuming is declared as private
• myElephant.setAge(72); // will work
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructore, copy constructor, and assignment operator
• Const
• Template
INHERITANCE
• The power of object-oriented languages
• Enables reuse of fields/methods
• All parent fields included in child instantiation
• Protected and public fields and methods directly accessible to child
• Parent methods may be overridden
• New fields and methods may be added to the child
• Multiple inheritance
INHERITANCE (CONT’D)
class classname: public parentname {
private:
….;
public:
….;
//access to parent methods through
// parentname::methodname …
}
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructore, copy constructor, and assignment operator
• Const
• Template
HEADER FILE
• For complex classes, the member functions are declared in a header file and
the member functions are implemented in a separate file.
• This allows people to look at the class definitions, and their member functions separately
• The header file needs to be included in your program when you use the
classes defined in the head file
#include “Segment.H”
#include <iostream>
# INCLUDE
Insert header file at this point.
Use library header.
HEADER GUARDS
#ifndef __SEGMENT_HEADER__
#define __SEGMENT_HEADER__
// contents of Segment.H
//...
#endif
• To ensure it is safe to include a file more than once.
HEADER GUARDS
#ifndef __SEGMENT_HEADER__
#define __SEGMENT_HEADER__
// contents of segment.H
//...
#endif
• To ensure it is safe to include a file more than once.
If this variable is
not defined…Define it.
End of guarded area.
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructore, copy constructor, and assignment operator
• Const
• Template
OUTPUT
#include<iostream>
Tell compiler that we are doing I/O
cout
Object to which we can send data.
<<
operator for sending data.
endl `n’ `t’
Special symbols that we can send.
FORMATTING OUTPUT
ios::left left justify the output
ios::right right justify the output
ios::scientific use scientific notation for numbers
ios::hex print numbers in hexadecimal base
ios::dec print numbers in decimal base
ios::uppercase print all characters in upper case
cout.setf(long flag) cout.unsetf(long flag)
Set different formatting
parameters for next output.
Disable these formatting
parameters.
EXAMPLE
#include<iostream.h>
main()
{
cout.width(10); //sets width to 10
cout << “hello” << endl;
cout.setf(ios::left);
cout << “hello” << endl;
cout << 16 << endl;
cout.setf(ios::hex, ios::basefield);
cout << 16 << endl;
}
hello
hello
16
10
Output
INPUT
#include <iostream.h>
Tell the linker we are doing basic I/O
cin
The input object. It retrieves input from the keyboard
>>
The extractor operator.
EXAMPLE
#include <iostream.h>
main ()
{
int userInput;
cout << “Enter number:”;
cin >> userInput;
cout << “You entered ” <<
userInput << endl;
}
Enter number:12345
You entered 12345
Output
I/O FROM A FILE
• I/O from a file is done in a similar way.
#include <iostream.h>
#include <fstream.h>
main()
{
int inputNumber;
ofstream myOutputFile(“outfile”);
ifstream myInputFile(“infile”);
myOutputFile << “text to file.” << endl;
myInputFile >> inputNumber;
myOutputFile.close();
myInputFile.close();
}
#include<string>
#include<fstream>
#include<iostream>
#include<iomanip>
using namespace std;
int main(int argc, char *argv[])
{
// Check input
if(argc<2)
{
cout<<"Usage: "<<argv[0]<<" <filename>"<<endl;
return 0;
}
// Try to read from file
cout<<"Reading tokens from file'"<<argv[1]<<"':"<<endl;
ifstream in(argv[1]);
if(!in)
cout<<" - Could not read from file '"<<argv[1]<<"'."<<endl;
else
{
string token;
cout.setf(ios::right);
for(unsigned i=1; in>>token; i++)
cout<<setw(4)<<i<<": "<<token<<endl;
}
in.close();
cout<<endl;
// Allow user to enter a token
string text;
cout<<"Enter sometext: ";
getline(cin, text);
// Append new tokensto file
ofstream out(argv[1], ios::app);
if(out)
out<<endl<<text<<endl;
else
cout<<"- Could not writeto file'"<<argv[1]<<"'"<<endl;
out.close();
return 0;
}
This program reads a file
name given by the user and
the read token by token from
the file. The tokens are
printed to the standard
output.
The second half of the
algorithm reads a token from
a standard input and appends
it to the file that was given.
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructore, copy constructor, and assignment operator
• Const
• Template
WHAT IS A POINTER?
int x = 10;
int *p;
p = &x;
p gets the address of x in memory.
p
x10
WHAT IS A POINTER?
int x = 10;
int *p;
p = &x;
*p = 20;
*p is the value at the address p.
p
x20
WHAT IS A POINTER?
int x = 10;
int *p;
p = &x;
*p = 20;
Declares a pointer
to an integer
& is address operator
gets address of x
* dereference operator
gets value at p
A POINTER EXAMPLE
int main(){
int i, j;
int *pi, *pj;
i = 5;
j = i;
pi = &i;
pj = pi;
*pj = 4;
cout << i << “ “;
cout << j << “ “;
cout << *pi << “ “;
cout << *pj << endl;
return 0;
}
> 4, 5, 4, 4
ALLOCATING MEMORY USING NEW
Point *p = new Point(5, 5);
• Point is a class already defined
• new can be thought of a function with slightly strange syntax
• new allocates space to hold the object.
• new calls the object’s constructor.
• new returns a pointer to that object.
MEMORY ALLOCATION EXAMPLES
• new returns a pointer to the dynamically created object.
#include “Cow.h”
#include <iostream>
using namespace std;
int main(){
int *i = new int(12);
Cow *c = new Cow;
...
delete i;
delete c;
return 0;
}
PROBLEMS
• Dangling pointers
• Pointers to memory that has already been deallocated
• segmentation fault (core dump)... or worse....
• Memory leak
• Loosing pointers to dynamically allocated memory
• Substantial problem in many commercial products
• See Windows 98
• C++ HAS NO GARBAGE COLLECTION!
DANGLING POINTER EXAMPLES
int main(){
int *myNum = new int(12);
int *myOtherNum = myNum;
delete myNum;
cout << *myOtherNum << endl;
return 0;
}
int* badFunction(){
int num = 10;
return &num;
}
int* stillBad(int n){
n += 12;
return &n;
}
int main(){
int num = 12;
int *myNum = badFunction();
int *myOtherNum = stillBad(num);
cout << *myNum << “, “;
cout << *myOtherNum << endl;
return 0;
}
MEMORY LEAK EXAMPLES
int main(){
int *myNum = new int(12);
myNum = new int(10);
// Oops...
delete myNum;
return 0;
}
int evilFunction(){
int *i = new int(9);
return *i;
}
int main(){
int num = evilFunction();
// I’m loosing my memory!!
return 0;
}
DEALLOCATING MEMORY USING DELETE
// allocate memory
Point *p = new Point(5, 5);
...
// free the memory
delete p;
For every call to new, there must be
exactly one call to delete.
USING NEW WITH ARRAYS
int x = 10;
int* nums1 = new int[10]; // ok
int* nums2 = new int[x]; // ok
• Initializes an array of 10 integers on the heap.
• C++ equivalent of C
int* nums = (int*)malloc(x * sizeof(int));
USING NEW WITH MULTIDIMENSIONAL ARRAYS
int x = 3, y = 4;
int* nums3 = new int[x][4][5];// ok
int* nums4 = new int[x][y][5];// BAD!
• Initializes a multidimensional array
• Only the first dimension can be a variable. The rest must be constants.
• Use single dimension arrays to fake multidimensional ones
USING DELETE ON ARRAYS
// allocate memory
int* nums1 = new int[10];
int* nums3 = new int[x][4][5];
...
// free the memory
delete[] nums1;
delete[] nums3;
• Have to use delete[].
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructore, copy constructor, and assignment operator
• Const
• Template
CLASS DESTRUCTORS
• If a class dynamically
allocates memory, we
need a way to deallocate it
when it’s destroyed.
• Distructors called upon
distruction of an object
class MyClass{
public:
MyClass(){
// Constructor
}
~MyClass(){
// Destructor
}
...
};
DESTRUCTORS
• delete calls the object’s destructor.
• delete frees space occupied by the object.
• A destructor cleans up after the object.
• Releases resources such as memory.
DESTRUCTORS – AN EXAMPLE
class Segment
{
public:
Segment();
virtual ~Segment();
private:
Point *m_p0, *m_p1;
};
DESTRUCTORS – AN EXAMPLE
Segment::Segment()
{
m_p0 = new Point(0, 0);
m_p1 = new Point(1, 1);
}
Segment::~Segment()
{
delete m_p0;
delete m_p1;
}
COPY CONSTRUCTOR AND ASSIGNMENT OPERATOR
• Copy Constructor:
class Rooster{
public:
...
Rooster(const Rooster &rhs){
// Do your deep copy
}
...
};
...
// Usage
Rooster r(12);
Rooster s(r);
• Assignment Operator:
class Rooster{
public:
...
Rooster&
operator=(const Rooster &rhs){
// Copy stuff
}
...
};
...
// Usage
Rooster r(12), s(10);
r = s;
CANONICAL FORM
• All classes should have
each of the following:
• Default constructor
• Copy constructor
• Assignment operator
• Destructor
// Canonical Cow
class Cow{
public:
Cow(){...}
Cow(const Cow &rhs){...}
Cow& operator=(const Cow &c)
{...}
~Cow(){...}
...
};
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructore, copy constructor, and assignment operator
• Const
• Template
INTRODUCING: CONST
void Math::printSquare(const int& i)
{
i = i*i;
cout << i << endl;
}
int main()
{
int i = 5;
Math::printSquare(i);
Math::printCube(i);
}
Won’t compile.
HOW DOES CONST WORK HERE?
void Math::printSquares(const int& j, int& k)
{
k = k*k; // Does this compile?
cout << j*j << “, “ << k << endl;
}
int main()
{
int i = 5;
Math::printSquares(i, i);
}
RETURNING CONST REFERENCES IS OK
class Point
{
point:
const double& getX() const;
const double& getY() const;
void move(double dx, double dy);
private:
double m_x, m_y;
}
const double& Point::getX()
const
{
return m_x;
}
Constant function,
also called accessor
Return a reference to a
constant double
NAMESPACES
• Namespaces are kind of like packages in Java
• Reduces naming conflicts
• Most standards C++ routines and classes and under the std
namespace
USING NAMESPACE
#include <iostream>
...
std::string question =
“How do I prevent RSI?”;
std::cout << question << std::endl;
using namespace std;
string answer = “Type less.”;
cout << answer << endl;
But, not in header files!
OUTLINE
• History and overview
• Basic features
• Parameter passing
• Classes
• Inheritance and virtual
• Header file
• IO
• Memory Management
• Big three: destructor, copy constructor, and assignment operator
• Const
• Template
TEMPLATE
What exactly are templates for, and why learn them?
• Limited Generic Programming (polymorphism)
Some functions have the same semantic meaning for some (if not all) data
types. For instance, a function print() should display a sensible
representation of anything passed in. Ideally, it shouldn’t need to be
rewritten for each possible type.
• Less repetitive code
Code that only differs in the data type it handles does not have to be
rewritten for each and every data type you want to handle. It’s easier to
read and maintain since one piece of code is used for everything
EXAMPLE: A SWAP FUNCTION
Naive method – write an overloaded function for each type
void swap(int &a, int &b) {
int c = a;
a = b;
b = c;
}
void swap(T &a, T &b) {
T c = a;
a = b;
b = c;
}
Swap for integers Swap for an arbitrary type T
template <typename T>
void swap(T &a, T &b) {
T c = a;
a = b;
b = c;
}
This function can be used with any
type that supports assignment and can
be passed in as a non-const reference.
Problem: Oftentimes, it is nice to be able to swap the values of two
variables. This function’s behavior is similar for all data types. Templated
functions let you do that – in most cases without any syntax changes.
Template method – write one templated function
TEMPLATE SYNTAX: SWAP DISSECTED
template <typename T>
void swap(T &a, T &b) {
T c = a;
a = b;
b = c;
}
The template<…> line states that
everything in the following
declaration or definition is under
the subject of the template. (In this
case, the definition is the function
swap)
In here goes a list of “placeholders
variables.” In almost all cases, they
will be specified with either the
typename or class keywords.
These two keywords are
equivalent.
“Placeholder variables” have one value
within each template declaration. Think of
them as being replaced by whatever type
you specify the template to be.
TEMPLATE SYNTAX: USING IT
template <typename T>
void swap(T &a, T &b) {
T c = a;
a = b;
b = c;
}
Example:
double d1 = 4.5, d2 = 6.7;
swap(d1, d2);
Syntax
CLASS TEMPLATES: EXAMPLE
Example: A templated, dynamic, 2 dimensional array (Matrix)*
#ifndef MATRIX_H
#define MATRIX_H
template <typename T>
class Matrix {
public:
Matrix(int rows, int cols);
Matrix(const Matrix &other);
virtual ~Matrix();
Matrix& operator=(const Matrix &rhs);
T* operator[](int i);
int getRows() const;
int getCols() const;
protected:
void copy(const Matrix &other);
private:
Matrix();
int m_rows;
int m_cols;
T *m_linArray;
};
#endif /* MATRIX_H */
File: Matrix.h
Notice the only addition to
the class definition is the
line:
template <typename T>
Within the the
definition block,
the placeholder
has can be used as
a data type. When
the template is
specialized, it
takes on the value
of the
specialization.
template <typename T>
T* Matrix<T>::operator[](int i) {
return m_linArray + (i*m_cols);
}
template <typename T>
void
Matrix<T>::copy(const Matrix &other) {
m_rows = other.m_rows;
m_cols = other.m_cols;
int size = m_rows * m_cols;
m_linArray = new T[size];
for( int i=0; i < size; i++ ) {
m_linArray[i] =
other.m_linArray[i];
}
}
template <typename T>
int Matrix<T>::getRows() const {
return m_rows;
}
template <typename T>
int Matrix<T>::getCols() const {
return m_cols;
}
CLASS TEMPLATES: EXAMPLE CONT’D
#include "Matrix.h"
template <typename T>
Matrix<T>::Matrix()
{}
template <typename T>
Matrix<T>::Matrix(int rows, int cols) {
m_rows = rows;
m_cols = cols;
m_linArray = new T[m_rows * m_cols];
}
template <typename T>
Matrix<T>::Matrix(const Matrix &other) {
copy(other);
}
template <typename T>
Matrix<T>::~Matrix() {
delete[] m_linArray;
}
template <typename T>
Matrix<T>&
Matrix<T>::operator=(const Matrix &other) {
if( this != &other ) {
delete[] m_linArray;
copy(other);
}
return *this;
} File: Matrix.cc
template <typename T>
Matrix<T>&
Matrix<T>::operator=(const Matrix &other) {
if( this != &other ) {
this->~Matrix();
copy(other);
}
return *this;
}
CLASS TEMPLATES: MEMBER FUNCTIONS DISSECTED
Again, a templated class name by itself
has no meaning (eg. Matrix by itself
means nothing). It only gets meaning
through specialization, explicit or implicit.
Thus, when referring to an instance of a
templated class (a specific specialization),
the class name must be explicitly
specialized.
Here, the template has been
implicitly specialized by its context.
It is within the specialization region
of the class scope. Thus it does not
need the template arguments. For a
class definition, the specialization
region is the class block.
specialization region of
Matrix<T>::
Notice that the
specialization
region does not include the
return type. Thus the return
type needs explicit
specialization
This may be
obvious, but
remember that
though constructors
and destructors
have the same name
as a the class
template, they are
functions and do not
need to be
specialized.
CLASS TEMPLATES: USAGE
•Templated classes must be explicitly specialized. Thus, to create a 2
dimensional Matrix of doubles using the last example, the syntax would be:
Matrix<double> m(3,3);
Syntax
STL
• Allows you to easily store anything without writing a container yourself
• Will give you the most hideous compile errors ever if you use them
incorrectly.
STL EXAMPLE
using namespace std;
typedef list<int> intlist;
typedef intlist::iterator intlistIter;
intlist v;
v.push_back(4);
intlistIter a;
for(a = v.begin(); a != v.end(); ++a)
{
int c = (*a);
}
• Now compile and run a simple c++ program
COMPILATION MODEL
• Preprocessor
• Resolves all preprocessor directives
• #include, #define macros, #ifdef, etc.
• Compiler
• Converts text into object files
• May have unresolved interobject references
• Linker
• Resolves all interobject references (or gives you a linker error)
• Creates the binary executable
• Loader
• Loads the program into RAM and runs the main() function
COMPILATION
Preprocessor
Inlines #includes etc.
Compiler
Translates to machine code
Associates calls with functions
Linker
Associates functions with definitions
Object files
Executable
External Libraries, libc.so, libcs123.so
HELLOWORLD.CPP
#include <iostream> // For cout
using namespace std;
int main(){
cout << "Hello World!" << endl;
return 0;
}
COMPILING WITH G++
ix$ ls
hello.cpp
ix$ ls
hello.cpp
ix$ g++ hello.cpp
ix$ ls
a.out* hello.cpp
ix$ g++ -c hello.cpp
ix$ ls
a.out* hello.cpp hello.o
ix$ g++ -o hello hello.cpp
ix$ ./hello
Hello World!
MAKEFILE
> make
SIMPLE MAKEFILE
All: hello
hello: hello.o
g++ -o hello hello.o
hello.o: hello.cpp
g++ -c hello.cpp
ix$ ls
hello.cpp makefile
ix$ make
g++ -c hello.cpp
g++ -o hello hello.o
ix$ ls
hello* hello.cpp hello.o makefile
ix$ ./hello
Hello World!
C++ overview

More Related Content

What's hot

Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
mircodotta
 

What's hot (19)

Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In Practice
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala: functional programming for the imperative mind
Scala: functional programming for the imperative mindScala: functional programming for the imperative mind
Scala: functional programming for the imperative mind
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Strong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisationStrong typing : adoption, adaptation and organisation
Strong typing : adoption, adaptation and organisation
 
10 Things I Hate About Scala
10 Things I Hate About Scala10 Things I Hate About Scala
10 Things I Hate About Scala
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
From Ruby to Scala
From Ruby to ScalaFrom Ruby to Scala
From Ruby to Scala
 
Beginning Java for .NET developers
Beginning Java for .NET developersBeginning Java for .NET developers
Beginning Java for .NET developers
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
 
Rapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on RailsRapid Application Development using Ruby on Rails
Rapid Application Development using Ruby on Rails
 
Groovy Programming Language
Groovy Programming LanguageGroovy Programming Language
Groovy Programming Language
 
Let’s have some fun with Power Query M language
Let’s have some fun with Power Query M languageLet’s have some fun with Power Query M language
Let’s have some fun with Power Query M language
 
Strong typing @ php leeds
Strong typing  @ php leedsStrong typing  @ php leeds
Strong typing @ php leeds
 
D programming language
D programming languageD programming language
D programming language
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Quick introduction to scala
Quick introduction to scalaQuick introduction to scala
Quick introduction to scala
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 

Viewers also liked

C++ Overview
C++ OverviewC++ Overview
C++ Overview
kelleyc3
 
Optical fibre cable
Optical fibre cableOptical fibre cable
Optical fibre cable
Aman Agarwal
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
TAlha MAlik
 
Smart watch
Smart watchSmart watch
Smart watch
SHEEMA90
 
Scanner presentation
Scanner presentationScanner presentation
Scanner presentation
Aniket Menon
 

Viewers also liked (20)

C++ Basics
C++ BasicsC++ Basics
C++ Basics
 
Managing bitlocker with mbam
Managing bitlocker with mbamManaging bitlocker with mbam
Managing bitlocker with mbam
 
Deploying Microsoft BitLocker
Deploying Microsoft BitLockerDeploying Microsoft BitLocker
Deploying Microsoft BitLocker
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
 
Optical fibre cable
Optical fibre cableOptical fibre cable
Optical fibre cable
 
C++ overloading
C++ overloadingC++ overloading
C++ overloading
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
Optical drive
Optical driveOptical drive
Optical drive
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Virtual Personal Assistant
Virtual Personal AssistantVirtual Personal Assistant
Virtual Personal Assistant
 
Sim cards
Sim cardsSim cards
Sim cards
 
How Siri Works
How Siri WorksHow Siri Works
How Siri Works
 
Graphics processing unit ppt
Graphics processing unit pptGraphics processing unit ppt
Graphics processing unit ppt
 
Google Cloud Print
Google Cloud PrintGoogle Cloud Print
Google Cloud Print
 
Lost Report of SIM Card
Lost Report of SIM CardLost Report of SIM Card
Lost Report of SIM Card
 
Smart watch
Smart watchSmart watch
Smart watch
 
Scanner presentation
Scanner presentationScanner presentation
Scanner presentation
 
Virtual personal assistant
Virtual personal assistantVirtual personal assistant
Virtual personal assistant
 
Introduction to Programming Languages
Introduction to Programming LanguagesIntroduction to Programming Languages
Introduction to Programming Languages
 
Optical Computing
Optical ComputingOptical Computing
Optical Computing
 

Similar to C++ overview

CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptx
JEEVANANTHAMG6
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
TAlha MAlik
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
Adeel Hamid
 

Similar to C++ overview (20)

c++ ppt.ppt
c++ ppt.pptc++ ppt.ppt
c++ ppt.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
c++ Unit I.pptx
c++ Unit I.pptxc++ Unit I.pptx
c++ Unit I.pptx
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
lecture02-cpp.ppt
lecture02-cpp.pptlecture02-cpp.ppt
lecture02-cpp.ppt
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
UsingCPP_for_Artist.ppt
UsingCPP_for_Artist.pptUsingCPP_for_Artist.ppt
UsingCPP_for_Artist.ppt
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
CLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptxCLEAN CODING AND DEVOPS Final.pptx
CLEAN CODING AND DEVOPS Final.pptx
 
Cs1123 11 pointers
Cs1123 11 pointersCs1123 11 pointers
Cs1123 11 pointers
 
C language
C languageC language
C language
 
Programming Language
Programming  LanguageProgramming  Language
Programming Language
 
C++primer
C++primerC++primer
C++primer
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
C programming language tutorial
C programming language tutorialC programming language tutorial
C programming language tutorial
 
Developer’s viewpoint on swift programming language
Developer’s viewpoint on swift programming languageDeveloper’s viewpoint on swift programming language
Developer’s viewpoint on swift programming language
 
Return of c++
Return of c++Return of c++
Return of c++
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 

More from Prem Ranjan (6)

Self powered wireless sensor for indoor environment monitoring
Self powered wireless sensor for indoor environment monitoringSelf powered wireless sensor for indoor environment monitoring
Self powered wireless sensor for indoor environment monitoring
 
Verilog coding
Verilog codingVerilog coding
Verilog coding
 
Digital signal processors
Digital signal processorsDigital signal processors
Digital signal processors
 
final year major project
final year major projectfinal year major project
final year major project
 
Plasma antenna
Plasma antennaPlasma antenna
Plasma antenna
 
4 g
4 g4 g
4 g
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 

Recently uploaded (20)

microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 

C++ overview

  • 1. DATA STRUCTURES & ALGORITHMS C++ WARM-UP - PREM RANJAN
  • 2. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructor, copy constructor, and assignment operator • Const • Template
  • 3. HISTORY OF C++ • 1972: C language developed at Bell Labs • Dennis Ritchie wrote C for Unix OS • Needed C for work with Unix • late 70s: C becomes popular for OS development by many vendors • Many variants of the language developed • ANSI standard C in 1987-89
  • 4. HISTORY OF C++ (CONTINUED) • early 80s: Bjarne Stroustrup adds OO features to C creating C++ • 90s: continued evolution of the language and its applications • preferred language for OS and low level programming • popular language for application development • low level control and high level power
  • 5. CONCEPTUALLY WHAT IS C++ • Alternatives: • is it C, with lots more options and features? • is it an OO programming language with C as its core? • is it a development environment? • On most systems it is a development environment, language, and library, used for both procedural and object oriented programming, that can be customized and extended as desired
  • 6. VERSIONS OF C++ • ANSI C++ • Microsoft C++ (MS Visual C++ 6.0) • Other vendors: Borland, Symantec, Turbo, … • Many older versions (almost annual) including different version of C too • Many vendor specific versions • Many platform specific versions • For this class: Unix / Linux based versions • g++
  • 7. CHARACTERISTICS OF C++ AS A COMPUTER LANGUAGE • Procedural • Object Oriented • Extensible • ...
  • 8. OTHER OO LANGUAGES • Smalltalk • pure OO language developed at PARC • Java • built on C/C++ • objects and data types • Eifel and others
  • 9. WHAT YOU CAN DO WITH C++ • Apps (standalone, Web apps, components) • Active desktop (Dynamic HTML, incl Web) • Create graphical apps • Data access (e-mail, files, ODBC) • Integrate components w/ other languages
  • 10. DISADVANTAGES OF C++ • Tends to be one of the less portable languages • Complicated? • 40 operators, intricate precedence, pointers, etc. • can control everything • many exceptions and special cases • tremendous libraries both standard, vendor specific, and available for purchase, but all are intricate • Aspects above can result in high maintenance costs
  • 11. ADVANTAGES OF C++ • Available on most machines • Can get good performance • Can get small size • Can manage memory effectively • Can control everything • Good supply of programmers • Suitable for almost any type of program (from systems programs to applications)
  • 12. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template
  • 13. PRIMITIVE TYPES • bool true or false (only C++) • char 8/16-bit • short 16-bit signed integer • int 32-bit signed integer • unsigned 32-bit unsigned integer • long 32 / 64-bit signed integer • float 32-bit floating point • double 64-bit floating point
  • 14. OPERATORS AND PRECEDENCE • [ ] . • to access arrays elements / to access object methods and fields • expr++ expr-- ++expr --expr ! • new (type)expr • * / % • + - • << >> (integers only) • < > >= <= • == != • &
  • 15. OPERATORS AND PRECEDENCE • ^ • | • && (booleans only) • || (booleans only) • ?: • = += -= *= …. • C++ allows operator overloading
  • 16. PRECEDENCE EXAMPLE • What is: 5 + 21 / 4 % 3 • = 5 + (21 / 4) % 3 • = 5 + ( 5 % 3) • = 5 + 2 • = 7
  • 17. EXPLICIT CASTING • (type) expression • Possible among all integer and float types • Possible among some class references • E.g. int i = (int) ( (double)5 / (double)3 )
  • 18. IMPLICIT CASTING • Applied automatically provided there is no loss of precision • float  double • int  double • Example • int iresult, i=3; • double dresult, d=3.2; • dresult = i/d => implicit casting dresult=0.9375 • iresult = i/d => error! Why? Loss in precision, needs explicit casting
  • 19. CONTROL FLOW if (boolean) statement; else if(boolean) statement2; else statement3; Booleans only, not integers! • if (i > 0)  correct • if (i = 2)  correct / incorrect ?
  • 20. SWITCH / CASE • switch (controlVar) { case 'a' : statement-1 break; case 'b' : statement-2 break; default : statement-3 break; } • Do not forget the break command to avoid surprise result!
  • 22. SOME CONVENTIONS FOR VARIABLE NAMES • Use letters and numbers • Do not use special characters including spaces, dots, underlines, pound signs, etc. • The first letter will be lower case • Use variable names that are meaningful (except for occasional counters that we might call i, j, x, etc.) • You can concatenate words, and capitalize each after the first, e.g., bankBal, thisAcctNum, totAmt • If you abbreviate, be consistent. For example do not use both bankBal and totalBalance as variable names.
  • 23. SOME CONVENTIONS FOR STRUCT AND CLASS NAMES • In creating names of structs and classes, apply the same rules as for variable names, except the first character will be upper case • Example: • an object's name: myCar • the struct or class name: Car • Another Example: aPerson and Person
  • 24. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template
  • 25. PASSING PARAMETERS • C++ allows for three different ways of passing parameters: • Pass “by value” • E.g. foo (int n) • Appropriate for small objects (usually primitive types) that should not be altered by the function call • Pass “by constant reference” • E.g. foo(const T& myT) • Appropriate for large objects that should not be altered by the function call • Pass “by reference” • E.g. foo(bool & errFlag) • Appropriate for small objects that can be altered by the function call • Array types are always passed “by reference”
  • 26. PASSING BY VALUE void square(int i) { i = i*i; } int main() { int i = 5; square(i); cout << i << endl; }
  • 27. PASSING BY REFERENCE void square(int& i) { i = i*i; } int main() { int i = 5; square(i); cout << i << endl; }
  • 28. PASSING BY CONSTANT REFERENCE void square(const int& i) { i = i*i; } int main() { int i = 5; square(i); cout << i << endl; } Wont work, why?
  • 29. PASSING BY CONSTANT REFERENCE int square(const int& i) { return i*i; } int main() { int i = 5; cout << square(i) << endl; } Will it his work?
  • 30. WHAT IS A REFERENCE? • An alias – another name for an object. int x = 5; int &y = x; // y is a reference to x y = 10; • What happened to x? • What happened to y? – y is x.
  • 31. WHY ARE THEY USEFUL? • When passing argument of large size (class type), can save space • Sometimes need to change a value of an argument • Can be used to return more than one value (pass multiple parameters by reference)
  • 32. HOW ARE REFERENCES DIFFERENT FROM POINTERS? Reference Pointer int a = 10; int b = 20; int &c = a; c = b; What is the value of a? int a = 10; int b = 20; int *c = &a; c = &b;
  • 33. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template
  • 34. CLASSES • Provide a mechanism for defining classes of objects. • We can define the class of all computers to have certain characteristics. • An instance of a computer is your home PC. • Classes contain member variables and member functions.
  • 35. CLASSES IN C++: WHY CREATE CLASSES / OBJECTS? • Keeps all related info (i.e., data) together • Refer to all the related info by one name • Protect the information • Hide methods that use or change the info • Keep methods together with their related info
  • 36. EXAMPLE OF BENEFITS OF CREATING AN OBJECT • Keeps all related info (i.e., data) together Person thisPerson; Person thisPerson = new Person ("Bill", "Clinton", 52); • Refer to all the related info by one name thisPerson • Protect the information lastName = "Dole"; //normally data members are private, and member functions are public
  • 37. CLASSES AND OBJECTS Mammals Humans Tigers Hank Peggy Tony class class class inherits inherits instance-ofinstance-of
  • 38. EXAMPLE OF A SIMPLE CLASS class Change { private: int quarters; int dimes; public: int getQuarters() {return quarters;} int getDimes() {return dimes;} void setQuarters(int aQuarters) {quarters = aQuarters;} …... void printChange() {cout << "nQuarters: " << quarters << " Dimes: " << dimes << endl; } };
  • 39. MORE CLASS EXAMPLE class human { // this data is private to instances of the class int height; char name[]; int weight; public: void setHeight(int heightValue); int getHeight(); };
  • 40. FUNCTION DEFINITIONS void human::setHeight(int heightValue) { if (heightValue > 0) height = heightValue; else height = 0; } int human::getHeight() { return(height); }
  • 41. EXAMPLE // first we define the variables. int height = 72; int result = 0; human hank; //set our human’s height hank.setHeight(height); //get his height result = hank.getHeight(); cout << “Hank is = “ << result << “inches tall” << endl; Hank is 72 inches tall Output
  • 42. INSTANTIATING AN OBJECT • The class definition does not create any objects • Instantiating and constructing are equivalent words for building a new object based on the model (i.e., template) of the class • Instantiating is done just like declaring a variable of a built in data type • Instantiating is done by a constructor (sometimes called a constructor method) • If the "class provider" does not provide a constructor, then the C++ compiler provides a default one automatically • The default constructor does not provide values to the data members (i.e. the instance variables)
  • 43. INSTANTIATING AN OBJECT (MORE) • When the object is instantiated, memory is allocated • Example of instantiation (implicit call of constructor) Car myCar; Elephant oneElephant, twoElephant; • No initialization takes place • Each object has its own memory allocation • oneElephant and twoElephant are separate objects in different locations in memory • Each is addressed individually by name or location • Each data member is addressed individually using the object name and the data member name, for example: oneElephant.age twoElephant.name
  • 44. REFERENCING AN OBJECT • Each object has a name (or a location) which is assigned when the object is instantiated • private data members are accessible only within the class • since most data members are private, that means that these data items are accessed generally by means of member functions • myElephant.age = 72; //won't work, assuming is declared as private • myElephant.setAge(72); // will work
  • 45. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template
  • 46. INHERITANCE • The power of object-oriented languages • Enables reuse of fields/methods • All parent fields included in child instantiation • Protected and public fields and methods directly accessible to child • Parent methods may be overridden • New fields and methods may be added to the child • Multiple inheritance
  • 47. INHERITANCE (CONT’D) class classname: public parentname { private: ….; public: ….; //access to parent methods through // parentname::methodname … }
  • 48. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template
  • 49. HEADER FILE • For complex classes, the member functions are declared in a header file and the member functions are implemented in a separate file. • This allows people to look at the class definitions, and their member functions separately • The header file needs to be included in your program when you use the classes defined in the head file
  • 50. #include “Segment.H” #include <iostream> # INCLUDE Insert header file at this point. Use library header.
  • 51. HEADER GUARDS #ifndef __SEGMENT_HEADER__ #define __SEGMENT_HEADER__ // contents of Segment.H //... #endif • To ensure it is safe to include a file more than once.
  • 52. HEADER GUARDS #ifndef __SEGMENT_HEADER__ #define __SEGMENT_HEADER__ // contents of segment.H //... #endif • To ensure it is safe to include a file more than once. If this variable is not defined…Define it. End of guarded area.
  • 53. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template
  • 54. OUTPUT #include<iostream> Tell compiler that we are doing I/O cout Object to which we can send data. << operator for sending data. endl `n’ `t’ Special symbols that we can send.
  • 55. FORMATTING OUTPUT ios::left left justify the output ios::right right justify the output ios::scientific use scientific notation for numbers ios::hex print numbers in hexadecimal base ios::dec print numbers in decimal base ios::uppercase print all characters in upper case cout.setf(long flag) cout.unsetf(long flag) Set different formatting parameters for next output. Disable these formatting parameters.
  • 56. EXAMPLE #include<iostream.h> main() { cout.width(10); //sets width to 10 cout << “hello” << endl; cout.setf(ios::left); cout << “hello” << endl; cout << 16 << endl; cout.setf(ios::hex, ios::basefield); cout << 16 << endl; } hello hello 16 10 Output
  • 57. INPUT #include <iostream.h> Tell the linker we are doing basic I/O cin The input object. It retrieves input from the keyboard >> The extractor operator.
  • 58. EXAMPLE #include <iostream.h> main () { int userInput; cout << “Enter number:”; cin >> userInput; cout << “You entered ” << userInput << endl; } Enter number:12345 You entered 12345 Output
  • 59. I/O FROM A FILE • I/O from a file is done in a similar way. #include <iostream.h> #include <fstream.h> main() { int inputNumber; ofstream myOutputFile(“outfile”); ifstream myInputFile(“infile”); myOutputFile << “text to file.” << endl; myInputFile >> inputNumber; myOutputFile.close(); myInputFile.close(); }
  • 60. #include<string> #include<fstream> #include<iostream> #include<iomanip> using namespace std; int main(int argc, char *argv[]) { // Check input if(argc<2) { cout<<"Usage: "<<argv[0]<<" <filename>"<<endl; return 0; } // Try to read from file cout<<"Reading tokens from file'"<<argv[1]<<"':"<<endl; ifstream in(argv[1]); if(!in) cout<<" - Could not read from file '"<<argv[1]<<"'."<<endl; else { string token; cout.setf(ios::right); for(unsigned i=1; in>>token; i++) cout<<setw(4)<<i<<": "<<token<<endl; } in.close(); cout<<endl; // Allow user to enter a token string text; cout<<"Enter sometext: "; getline(cin, text); // Append new tokensto file ofstream out(argv[1], ios::app); if(out) out<<endl<<text<<endl; else cout<<"- Could not writeto file'"<<argv[1]<<"'"<<endl; out.close(); return 0; } This program reads a file name given by the user and the read token by token from the file. The tokens are printed to the standard output. The second half of the algorithm reads a token from a standard input and appends it to the file that was given.
  • 61. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template
  • 62. WHAT IS A POINTER? int x = 10; int *p; p = &x; p gets the address of x in memory. p x10
  • 63. WHAT IS A POINTER? int x = 10; int *p; p = &x; *p = 20; *p is the value at the address p. p x20
  • 64. WHAT IS A POINTER? int x = 10; int *p; p = &x; *p = 20; Declares a pointer to an integer & is address operator gets address of x * dereference operator gets value at p
  • 65. A POINTER EXAMPLE int main(){ int i, j; int *pi, *pj; i = 5; j = i; pi = &i; pj = pi; *pj = 4; cout << i << “ “; cout << j << “ “; cout << *pi << “ “; cout << *pj << endl; return 0; } > 4, 5, 4, 4
  • 66. ALLOCATING MEMORY USING NEW Point *p = new Point(5, 5); • Point is a class already defined • new can be thought of a function with slightly strange syntax • new allocates space to hold the object. • new calls the object’s constructor. • new returns a pointer to that object.
  • 67. MEMORY ALLOCATION EXAMPLES • new returns a pointer to the dynamically created object. #include “Cow.h” #include <iostream> using namespace std; int main(){ int *i = new int(12); Cow *c = new Cow; ... delete i; delete c; return 0; }
  • 68. PROBLEMS • Dangling pointers • Pointers to memory that has already been deallocated • segmentation fault (core dump)... or worse.... • Memory leak • Loosing pointers to dynamically allocated memory • Substantial problem in many commercial products • See Windows 98 • C++ HAS NO GARBAGE COLLECTION!
  • 69. DANGLING POINTER EXAMPLES int main(){ int *myNum = new int(12); int *myOtherNum = myNum; delete myNum; cout << *myOtherNum << endl; return 0; } int* badFunction(){ int num = 10; return &num; } int* stillBad(int n){ n += 12; return &n; } int main(){ int num = 12; int *myNum = badFunction(); int *myOtherNum = stillBad(num); cout << *myNum << “, “; cout << *myOtherNum << endl; return 0; }
  • 70. MEMORY LEAK EXAMPLES int main(){ int *myNum = new int(12); myNum = new int(10); // Oops... delete myNum; return 0; } int evilFunction(){ int *i = new int(9); return *i; } int main(){ int num = evilFunction(); // I’m loosing my memory!! return 0; }
  • 71. DEALLOCATING MEMORY USING DELETE // allocate memory Point *p = new Point(5, 5); ... // free the memory delete p; For every call to new, there must be exactly one call to delete.
  • 72. USING NEW WITH ARRAYS int x = 10; int* nums1 = new int[10]; // ok int* nums2 = new int[x]; // ok • Initializes an array of 10 integers on the heap. • C++ equivalent of C int* nums = (int*)malloc(x * sizeof(int));
  • 73. USING NEW WITH MULTIDIMENSIONAL ARRAYS int x = 3, y = 4; int* nums3 = new int[x][4][5];// ok int* nums4 = new int[x][y][5];// BAD! • Initializes a multidimensional array • Only the first dimension can be a variable. The rest must be constants. • Use single dimension arrays to fake multidimensional ones
  • 74. USING DELETE ON ARRAYS // allocate memory int* nums1 = new int[10]; int* nums3 = new int[x][4][5]; ... // free the memory delete[] nums1; delete[] nums3; • Have to use delete[].
  • 75. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template
  • 76. CLASS DESTRUCTORS • If a class dynamically allocates memory, we need a way to deallocate it when it’s destroyed. • Distructors called upon distruction of an object class MyClass{ public: MyClass(){ // Constructor } ~MyClass(){ // Destructor } ... };
  • 77. DESTRUCTORS • delete calls the object’s destructor. • delete frees space occupied by the object. • A destructor cleans up after the object. • Releases resources such as memory.
  • 78. DESTRUCTORS – AN EXAMPLE class Segment { public: Segment(); virtual ~Segment(); private: Point *m_p0, *m_p1; };
  • 79. DESTRUCTORS – AN EXAMPLE Segment::Segment() { m_p0 = new Point(0, 0); m_p1 = new Point(1, 1); } Segment::~Segment() { delete m_p0; delete m_p1; }
  • 80. COPY CONSTRUCTOR AND ASSIGNMENT OPERATOR • Copy Constructor: class Rooster{ public: ... Rooster(const Rooster &rhs){ // Do your deep copy } ... }; ... // Usage Rooster r(12); Rooster s(r); • Assignment Operator: class Rooster{ public: ... Rooster& operator=(const Rooster &rhs){ // Copy stuff } ... }; ... // Usage Rooster r(12), s(10); r = s;
  • 81. CANONICAL FORM • All classes should have each of the following: • Default constructor • Copy constructor • Assignment operator • Destructor // Canonical Cow class Cow{ public: Cow(){...} Cow(const Cow &rhs){...} Cow& operator=(const Cow &c) {...} ~Cow(){...} ... };
  • 82. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructore, copy constructor, and assignment operator • Const • Template
  • 83. INTRODUCING: CONST void Math::printSquare(const int& i) { i = i*i; cout << i << endl; } int main() { int i = 5; Math::printSquare(i); Math::printCube(i); } Won’t compile.
  • 84. HOW DOES CONST WORK HERE? void Math::printSquares(const int& j, int& k) { k = k*k; // Does this compile? cout << j*j << “, “ << k << endl; } int main() { int i = 5; Math::printSquares(i, i); }
  • 85. RETURNING CONST REFERENCES IS OK class Point { point: const double& getX() const; const double& getY() const; void move(double dx, double dy); private: double m_x, m_y; } const double& Point::getX() const { return m_x; } Constant function, also called accessor Return a reference to a constant double
  • 86. NAMESPACES • Namespaces are kind of like packages in Java • Reduces naming conflicts • Most standards C++ routines and classes and under the std namespace
  • 87. USING NAMESPACE #include <iostream> ... std::string question = “How do I prevent RSI?”; std::cout << question << std::endl; using namespace std; string answer = “Type less.”; cout << answer << endl; But, not in header files!
  • 88. OUTLINE • History and overview • Basic features • Parameter passing • Classes • Inheritance and virtual • Header file • IO • Memory Management • Big three: destructor, copy constructor, and assignment operator • Const • Template
  • 89. TEMPLATE What exactly are templates for, and why learn them? • Limited Generic Programming (polymorphism) Some functions have the same semantic meaning for some (if not all) data types. For instance, a function print() should display a sensible representation of anything passed in. Ideally, it shouldn’t need to be rewritten for each possible type. • Less repetitive code Code that only differs in the data type it handles does not have to be rewritten for each and every data type you want to handle. It’s easier to read and maintain since one piece of code is used for everything
  • 90. EXAMPLE: A SWAP FUNCTION Naive method – write an overloaded function for each type void swap(int &a, int &b) { int c = a; a = b; b = c; } void swap(T &a, T &b) { T c = a; a = b; b = c; } Swap for integers Swap for an arbitrary type T template <typename T> void swap(T &a, T &b) { T c = a; a = b; b = c; } This function can be used with any type that supports assignment and can be passed in as a non-const reference. Problem: Oftentimes, it is nice to be able to swap the values of two variables. This function’s behavior is similar for all data types. Templated functions let you do that – in most cases without any syntax changes. Template method – write one templated function
  • 91. TEMPLATE SYNTAX: SWAP DISSECTED template <typename T> void swap(T &a, T &b) { T c = a; a = b; b = c; } The template<…> line states that everything in the following declaration or definition is under the subject of the template. (In this case, the definition is the function swap) In here goes a list of “placeholders variables.” In almost all cases, they will be specified with either the typename or class keywords. These two keywords are equivalent. “Placeholder variables” have one value within each template declaration. Think of them as being replaced by whatever type you specify the template to be.
  • 92. TEMPLATE SYNTAX: USING IT template <typename T> void swap(T &a, T &b) { T c = a; a = b; b = c; } Example: double d1 = 4.5, d2 = 6.7; swap(d1, d2); Syntax
  • 93. CLASS TEMPLATES: EXAMPLE Example: A templated, dynamic, 2 dimensional array (Matrix)* #ifndef MATRIX_H #define MATRIX_H template <typename T> class Matrix { public: Matrix(int rows, int cols); Matrix(const Matrix &other); virtual ~Matrix(); Matrix& operator=(const Matrix &rhs); T* operator[](int i); int getRows() const; int getCols() const; protected: void copy(const Matrix &other); private: Matrix(); int m_rows; int m_cols; T *m_linArray; }; #endif /* MATRIX_H */ File: Matrix.h Notice the only addition to the class definition is the line: template <typename T> Within the the definition block, the placeholder has can be used as a data type. When the template is specialized, it takes on the value of the specialization.
  • 94. template <typename T> T* Matrix<T>::operator[](int i) { return m_linArray + (i*m_cols); } template <typename T> void Matrix<T>::copy(const Matrix &other) { m_rows = other.m_rows; m_cols = other.m_cols; int size = m_rows * m_cols; m_linArray = new T[size]; for( int i=0; i < size; i++ ) { m_linArray[i] = other.m_linArray[i]; } } template <typename T> int Matrix<T>::getRows() const { return m_rows; } template <typename T> int Matrix<T>::getCols() const { return m_cols; } CLASS TEMPLATES: EXAMPLE CONT’D #include "Matrix.h" template <typename T> Matrix<T>::Matrix() {} template <typename T> Matrix<T>::Matrix(int rows, int cols) { m_rows = rows; m_cols = cols; m_linArray = new T[m_rows * m_cols]; } template <typename T> Matrix<T>::Matrix(const Matrix &other) { copy(other); } template <typename T> Matrix<T>::~Matrix() { delete[] m_linArray; } template <typename T> Matrix<T>& Matrix<T>::operator=(const Matrix &other) { if( this != &other ) { delete[] m_linArray; copy(other); } return *this; } File: Matrix.cc
  • 95. template <typename T> Matrix<T>& Matrix<T>::operator=(const Matrix &other) { if( this != &other ) { this->~Matrix(); copy(other); } return *this; } CLASS TEMPLATES: MEMBER FUNCTIONS DISSECTED Again, a templated class name by itself has no meaning (eg. Matrix by itself means nothing). It only gets meaning through specialization, explicit or implicit. Thus, when referring to an instance of a templated class (a specific specialization), the class name must be explicitly specialized. Here, the template has been implicitly specialized by its context. It is within the specialization region of the class scope. Thus it does not need the template arguments. For a class definition, the specialization region is the class block. specialization region of Matrix<T>:: Notice that the specialization region does not include the return type. Thus the return type needs explicit specialization This may be obvious, but remember that though constructors and destructors have the same name as a the class template, they are functions and do not need to be specialized.
  • 96. CLASS TEMPLATES: USAGE •Templated classes must be explicitly specialized. Thus, to create a 2 dimensional Matrix of doubles using the last example, the syntax would be: Matrix<double> m(3,3); Syntax
  • 97. STL • Allows you to easily store anything without writing a container yourself • Will give you the most hideous compile errors ever if you use them incorrectly.
  • 98. STL EXAMPLE using namespace std; typedef list<int> intlist; typedef intlist::iterator intlistIter; intlist v; v.push_back(4); intlistIter a; for(a = v.begin(); a != v.end(); ++a) { int c = (*a); }
  • 99. • Now compile and run a simple c++ program
  • 100. COMPILATION MODEL • Preprocessor • Resolves all preprocessor directives • #include, #define macros, #ifdef, etc. • Compiler • Converts text into object files • May have unresolved interobject references • Linker • Resolves all interobject references (or gives you a linker error) • Creates the binary executable • Loader • Loads the program into RAM and runs the main() function
  • 101. COMPILATION Preprocessor Inlines #includes etc. Compiler Translates to machine code Associates calls with functions Linker Associates functions with definitions Object files Executable External Libraries, libc.so, libcs123.so
  • 102. HELLOWORLD.CPP #include <iostream> // For cout using namespace std; int main(){ cout << "Hello World!" << endl; return 0; }
  • 103. COMPILING WITH G++ ix$ ls hello.cpp ix$ ls hello.cpp ix$ g++ hello.cpp ix$ ls a.out* hello.cpp ix$ g++ -c hello.cpp ix$ ls a.out* hello.cpp hello.o ix$ g++ -o hello hello.cpp ix$ ./hello Hello World!
  • 105. SIMPLE MAKEFILE All: hello hello: hello.o g++ -o hello hello.o hello.o: hello.cpp g++ -c hello.cpp
  • 106. ix$ ls hello.cpp makefile ix$ make g++ -c hello.cpp g++ -o hello hello.o ix$ ls hello* hello.cpp hello.o makefile ix$ ./hello Hello World!