0% found this document useful (0 votes)
48 views9 pages

Lect 3 Slides

C++ is an object-oriented programming language that was created to be compatible with C while also supporting object-oriented programming features like classes and objects. Key concepts in C++ include data types, variables, expressions, control flow statements, functions, pointers, and arrays. Object-oriented features include classes, objects, constructors, and destructors. Namespaces help avoid name clashes between different code providers.

Uploaded by

duke
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)
48 views9 pages

Lect 3 Slides

C++ is an object-oriented programming language that was created to be compatible with C while also supporting object-oriented programming features like classes and objects. Key concepts in C++ include data types, variables, expressions, control flow statements, functions, pointers, and arrays. Object-oriented features include classes, objects, constructors, and destructors. Namespaces help avoid name clashes between different code providers.

Uploaded by

duke
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/ 9

C++

Overview
directives, such as
Object-oriented programming is a programming #include <string>
style that captures the behavior of the real world
in a way that hides detailed implementation, and Namespaces were introduced to provide a scope
it allows the problem solver to think in terms of that allows different code providers to avoid global
problem domain. C++ was created with two name clashes. The
goals: to make it compatible with ordinary C, namespace std;
and to extend C with OO constructs.
is reserved for use with the standard libraries. The
FAQ:http://www.parashift.com/c++-faq-lite/index.html
using declaration allows the identifiers found in
Object-oriented programming is a data-centered the standard library to be used without being qual-
view of programming, in which data and be- ified. Without this declaration the program would
havior are strongly linked. Data and be- have to use std::string.
havior are conceived of as classes whose in-
stances are objects. Objects are class vari- In OO terminology, a variable is called an object.
ables, and object-oriented programming allows A constructor is a member function whose job is
abstract data structures to be easily created and to initialize an object of its class. Constructors are
used. invoked whenever an object of its class is created.
A destructor is a member function whose job is
A C++ program is a collection of declarations to finalize a variable of its class. The destructor
and functions that begin executing with the is called implicitly when an automatic object goes
function main(). The program is compiled with out of scope.
a first phase executing any preprocessor
Spring 2010 COMPUTING METHODS IN HIGH ENERGY PHYSICS (page 1) S. Lehti and V. Karimäki
Lecture 3
C++
Native types the object.
int i;
The simple native types in C++ are bool,
A definition can also initialize the value of the vari-
double, int and char. These types have a set
able
of values and representation that is tied to the
int i = 0;
underlying machine architecture on which the
int i = 0,j;
compiler is running.
C++ declarations are themselves statements and
C++ simple types can be modified by the key-
they can occur throughout a block.
words short, long, signed and unsigned to
yield further simple types. An automatic type conversion can occur across as-
signments and mixed statements. A promotion
Fundamental data types
(widening) is usually well behaved, but demotions
bool (narrowing) can lose information. In mixed state-
char signed char unsigned char ments the type conversion follows promotion rules.
wchar t
short int long
unsigned short unsigned unsigned long In addition to implicit conversions, there are ex-
float double long double plicit conversions called casts.
static cast<double>(i)
A variable declaration associates a type with a const cast<double>(constVar)
variable name. A declaration of a variable con- Older C++ systems allow an unrestricted form of
stitutes a definition, if storage is allocated for it. cast with
The definition can be thought as a creating (type)expression or type(expression)
Spring 2010 COMPUTING METHODS IN HIGH ENERGY PHYSICS (page 2) S. Lehti and V. Karimäki
Lecture 3
C++
Expressions
The conditional operator ?: is a ternary operator,
The arithmetic operators in C++ are +,-,*,/,%.
taking three expressions as operands. In a con-
To raise to a power one can use the function
struct such as
pow. Arithmetic expressions are consistent with
expr1 ? expr2 : expr3
expected practise, with one important difference:
expr1 is evaluated first. If it is true, expr2 is eval-
division operator. The result of the division op-
uated, and that is the value of the conditional ex-
erator depends on its arguments
pression as a whole. If expr1 is false then expr3 is
a = 3 / 2;
evaluated. For example
a = 3 / 2.0;
x = (y < z) ? y : z;
Relational (<, >, <=, >=), equality (==,!=) assigns the smaller of two values to x.
and logical (!,&&,||) operators work as expected.
C++ provides also assignment operators that com-
In the evaluation of expressions that are the
bine an assingment and some operator like
operands of && and ||, the evaluation process
a += b; // a = a + b
stops as soon as the outcome is known. If expr1
a *= a + b; // a = a*(a+b)
is false, then in
i++; // i = i + 1
expr1 && expr2
i- -; // i = i - 1
expr2 will not be evaluated. Similarly, if expr1 is
j = i++; // j = i; i = i + 1
true, then in
j = ++i; // i = i + 1; j = i
expr1 || expr2
Notice that the two last examples are not equiva-
expr2 will not be evaluated since the value of the
lent.
logical expression is already determined.

Spring 2010 COMPUTING METHODS IN HIGH ENERGY PHYSICS (page 3) S. Lehti and V. Karimäki
Lecture 3
C++
Statements
Functions
The general forms of basic control flow state-
ments are A C++ program is made of one or more functions,
if ( condition ) statement one of which is main(). The form for a function
if ( condition ) statement1 else statement2 definition is
while ( condition ) statement type name(parameter-list) {
for (init; condition; increment) statement statements
do statement while ( condition ) }
switch ( condition ) statement The type specification that precedes the function
To interrupt the normal flow of control within a name is the return type, and the value is returned
loop, two special statements can be used: break with statement return. If the function does not
and continue return any value, the return type of the function is
void.
Example: a simple for loop
for(int i = 0; i < 3; i++){ The parameters in the parameter list can be given
cout << i << endl; default arguments
} void myFunction(int i, int j = 1){...}
Example: a while loop It is possible to overload functions
while (getline(file,line)){ void myFunction(int i){...}
cout << line.length() << endl; void myFunction(double d){...}
}

Spring 2010 COMPUTING METHODS IN HIGH ENERGY PHYSICS (page 4) S. Lehti and V. Karimäki
Lecture 3
C++

Pointers Arrays

Pointers are used to reference variables and ma- An array declaration is of the form
chine addresses. They can be used to access int a[size];
memory and manipulate addresses. Pointer vari- The values of an array can be accessed by a[expr],
ables can be declared in programs and then used where expr is an integer expression getting values
to take addresses as values. The declaration from 0 to (size-1). Arrays can be initialized by a
int* p; comma separated list
declares p to be of type pointer to int. The legal int a[3] = {1, 2, 3};
range of values for any pointer always includes or element by element a[0] = 1; a[1] = 2; a[2] =
the special address 0. 3;. Arrays can be thought of constant pointers.
int* p = &i; Pointer arithmetic provides an alternative to array
The variable p here can be thought of as referring indexing
to i or pointing to i or containing the address of int *p = a;
i. int *p = &a[0];

The dereferencing or indication operator * can The arrays can be of any type, including arrays of
be used to return the value of the variable the arrays. Multidimensional arrays can be formed by
pointer points to adding bracket pairs
int j = *p; int a[2][2]; // Not a[2,2]!
Here *p returns the value of variable i. int b[2][5][200];

Spring 2010 COMPUTING METHODS IN HIGH ENERGY PHYSICS (page 5) S. Lehti and V. Karimäki
Lecture 3
C++

Abstract Data Structures Member functions

ADT implementations are used for user-defined The concept of struct is augmented in C++ to
data types. A large part of the OO program de- allow functions to be members. The function dec-
sign process involves thinking up the appropriate laration is included in the structure declaration.
data structures for a problem. struct complex {
void reset(){
The structure type allows the programmer to re = 0;
aggregate components into a single named vari- im = 0;
able. A structure has components, called mem- }
bers, that are individually named. Since the double re,im;
members of a structure can be of various types, };
the programmer can create aggregates suitable
for describing complicated data. The member functions can be public or private.
Public members are visible outside the data struc-
Example: complex numbers ture, while private can be accessed only within the
struct complex { structure. Very often the data is hidden, and ac-
double re,im; cessed only by functions built for that purpose.
};
Hiding data allows more easily debugged and main-
complex c; tained code because errors and modifications are
c.re = 1; c.im = 2; localized.

Spring 2010 COMPUTING METHODS IN HIGH ENERGY PHYSICS (page 6) S. Lehti and V. Karimäki
Lecture 3
C++
Classes

Classes are introduced by a keyword class. Classes can nest. This means that there can be
They are a form of struct whose default privacy classes within classes. Referencing the outer or
specification is private. Thus struct and class inner variables is done with the scope resolution
can be used interchangeably with the appropri- operator.
ate access specifications. class X {
class complex { int i; // X::i
public: public:
void reset(){ class Y {
re = 0; int i; // X::Y::i
im = 0; };
} };
private:
The definition of a purely local class is unavailable
double re,im;
outside their local scope.
};
Static variables are shared by all variables of that
Class adds a new set of scope rules to those
class and stored in only one place.
of the kernel language. The scope resolution
operator :: comes in two forms: They keyword this denotes an implicitly declared
::i // refer to external scope self-referential pointer.
foo bar::i // refer to class scope

Spring 2010 COMPUTING METHODS IN HIGH ENERGY PHYSICS (page 7) S. Lehti and V. Karimäki
Lecture 3
C++
Input/Output
class X { Output is inserted into an object of type ostream,
public: declared in the header file iostream.h. An op-
X clone(){return (*this);} erator << is overloaded in this class to perform
}; output conversions from standard types.
std::cout << ”Hello world!” << std::endl;
The member functions can also be static and Input is inserted in istream, and operator >> is
const. A static member function can exist inde- overloaded to perform input conversions to stan-
pendent of any specific variables of the class type dard types.
being declared. Const member functions cannot std::cin >> i;
change the values of the data members. Writing Here ”using namespace std;” would allow us-
out const member functions and const param- ing these commands without the scope resolution
eter declarations is called const-correctness. It operator.
makes the code more robust. File i/o is handled by including fstream.h. To
class X { read a variable var from a file first open the file:
static int Y(); ifstream inFile(”filename”,ios::in);
int Z() const; inFile >> var;
}; A while loop can be made to read until EOF is
int X::Y(){} reached: while(!inFile.eof()){}
int X::Z() const {} It is also possible to read a whole line using
getline(ifstream,string).

Spring 2010 COMPUTING METHODS IN HIGH ENERGY PHYSICS (page 8) S. Lehti and V. Karimäki
Lecture 3
C++
#include ”SimpleMET.h”
Example: MET from high pt objects
SimpleMET::SimpleMET(){
File SimpleMET.h: etmiss.x = 0;
#ifndef SIMPLEMET H
etmiss.y = 0;
#define SIMPLEMET H
}
#include ”MyEvent.h” SimpleMET::∼SimpleMET(){}
class SimpleMET { void SimpleMET::Add(MyTrack track){
public: etmiss.x -= track.Px();
SimpleMET(); etmiss.y -= track.Py();
∼SimpleMET(); }
void Add(MyTrack); void SimpleMET::Add(MyJet jet){
void Add(MyJet); etmiss.x -= jet.Px();
etmiss.y -= jet.Py();
MyMET GetMET(); }
double Value();
MyMET SimpleMET::GetMET(){
private: return etmiss;
MyMET etmiss; }
}; double SimpleMET::Value(){
#endif
return etmiss.Value();
File SimpleMET.cc: }

Spring 2010 COMPUTING METHODS IN HIGH ENERGY PHYSICS (page 9) S. Lehti and V. Karimäki
Lecture 3

You might also like