+ All Categories
Home > Software > C++ Basics

C++ Basics

Date post: 12-Apr-2017
Category:
Upload: himanshu-sharma
View: 164 times
Download: 0 times
Share this document with a friend
46
Page 1 C++ basics By: Himanshu Sharma
Transcript
Page 1: C++ Basics

Page 1

C++ basics

By: Himanshu Sharma

Page 2: C++ Basics

Page 2

What is C++ ??? • C++ is a general purpose object oriented

programming language. • It is considered to be an intermediate level

language, as it encapsulates both high and low level language features.

•  Initially, the language was called 'C with classes’ as it had all properties of C language with an additional concept of 'classes’. However, it was renamed to C++ in 1983.

Page 3: C++ Basics

Page 3

Who discovered C++

•  In the early 1980's, also at Bell Laboratories, another programming language was created which was based upon the C language. 

• This new language was developed by Bjarne Stroustrup.

Page 4: C++ Basics

Page 4

Why C++ is called OOP ?• C++ is called object-oriented language

because C++ language views a problem in terms of objects involved rather than the procedure for doing it.

• C++ follows Object Oriented Programming concepts so we can say it is a Object Oriented Programming.

Page 5: C++ Basics

Page 5

Object Oriented Programming Concepts are:•

1.Class- is blue-print representing a group of objects that share common properties and relationship.2.Object- is an identifiable entity with some characteristics and behaviour.3.Data Abstraction- refers to representing essential features without including the background details.4.Encapsulation- wrapping up of data and functions in single class is known as encapsulation.5.Polymorphism- is the ability for a message or data to be processed in more than one form.6.Inheritnace- is the capability of one class of things to inherit properties from another class.

Page 6: C++ Basics

Page 6

C++ Character Set• Character set is a set of valid characters that a language can recognise.• A character represents any letter, digits, or any other sign. The C++ has the following character set :

Letters A-Z, a-zDigits 0-9Special symbols space + - * / () {} [] = : ; % # ! @ ^ & != - ?

# <= >=White spaces blank space, horizontal tab, carriage

return, newline, form feedOther characters C++ can process any of the 256 ASCII

characters as data or as literals.

Page 7: C++ Basics

Page 7

Some important terms1. Tokens- In a passage of text, individual words and

punctuation marks are called tokens or lexical units or lexical elements.

C++ has following tokens:I. KeywordsII. IdentifiersIII. LiteralsIV.PunctuatorsV. operators

Page 8: C++ Basics

Page 8

I. Keywords – keywords are the words that convey the special meaning to the language compiler. They are reserved for special purpose. EX- float, break, case, char, long etc.

II. Identifiers – identifiers are the fundamental building blocks of a program. It is an arbitrarily long sequence of letters and digits. EX- data1_4_7, myfile, etc.

III. Literals- literals are the data items that never change their value during a program run. Some kinds of literals are:

Integers- constantCharacter-constantFloating-constant String-literal

Page 9: C++ Basics

Page 9

IV.Punctuators- A punctuator is a token that has syntactic and semantic meaning to the compiler, but the exact significance depends on the context. A punctuator can also be a token that is used in the syntax of the pre-processor. EX- brackets [ ], comma , colon :

V. Operators- operators are tokens that trigger some computation when applied to variables and other objects in an expression. EX- @, #, %, +, ++, *, /= etc.

Page 10: C++ Basics

Page 10

Data Type A data type is a data storage format that can contain a specific type or range of values. Data types are of two types one is simple data type which contain:Int FloatDoubleCharVoid

Page 11: C++ Basics

Page 11

Second one is derived data type which contain:ArrayStructUnion EnumerationsPointersClass

Page 12: C++ Basics

Page 12

Polymorphism in C++

Page 13: C++ Basics

Page 13

Overview• Polymorphism means “Many forms”• OO Purists – “Only virtual methods” • Liberal C++ guys – Either virtual methods (Behavior), or templates (Types), or even function overloading for that matter (Behavior)• Generally accepted – virtual method based, and template based

Page 14: C++ Basics

Page 14

Kinds of Polymorphism• Runtime/Dynamic polymorphism (Based on virtual methods)• Compile time/Static polymorphism (Based on templates)• These 2 are largely orthogonal techniques, but many ways where one could be replaced with the other…and that’s where the confusion

Page 15: C++ Basics

Page 15

Any of them works - Contd• In the previous slide we have shown that templates aren’t restricted to polymorphism of type alone, but they also can be used for polymorphism of behavior• In fact the template version in the previous example yields much faster code than the virtual method equivalent • Much prevailing confusion about which technique to use in what situation

Page 16: C++ Basics

Page 16

Runtime polymorphism• Runtime binding between abstract type and concrete type• Enforces a common interface for all derived types via the base class• Enforces an ‘Is-A’ relationship• Used extensively in OO frameworks• Templates eating into parts of its territory

Page 17: C++ Basics

Page 17

Compile time Polymorphism• Compile time binding between abstract type and concrete type• Concrete types need not belong to the same inheritance hierarchy. They just need to meet the ‘Constraints’ imposed by the generic type. So, more generic than the virtuals• Foundation of ‘Generic programming’ or programming based on ‘Concepts’ (Eg: STL)• A very ‘Happening area’ in C++ right now (See TR1, Boost, C++0x...)

Page 18: C++ Basics

Page 18

Why all the excitement about templates?• Templates –

– Buy us generality in software, without the ‘Abstraction penalty’– Are type safe– Are non-intrusive– Allow both reference and value semantics unlike virtuals

Page 19: C++ Basics

Page 19

Design of reusable data structures – Inheritance or Templates?

Index Inheritance based approach Template based approach1 Slower (virtuals) Faster

2 Non type-safe (Crash!) Type safe

3 Intrusive (put an int/char inside a class and derive from base)

Non-Intrusive

4 Reference semantics only (leaks, crashes..)

Value or Reference semantics, both allowed

Page 20: C++ Basics

Page 20

Sure choice - Templates• So, templates lead to ‘Faster, Safer, and Easier to reuse’ data structures than inheritance• Using inheritance for designing generic data structures, is a common mistake in C++• Dates back to days where compiler support was bad for templates

Page 21: C++ Basics

Page 21

Why inheritance then?• Code and structure reuse from base classes• OO Frameworks

– Framework implementation requires ‘Heterogeneous containers’ – Reactor example– Often depend on polymorphic return types– Factory example– Can’t do that with templates

Page 22: C++ Basics

Page 22

Choosing your polymorphism• Don’t overuse inheritance (Implementing data structures using inheritance is an example of misuse of inheritance)• Evaluate if your design could be done using templates, they are faster and safer than virtuals.• Read up on templates and be aware of its pitfalls (Another class of mine will deal with that)

Page 23: C++ Basics

Page 23

Object counter• Synergy again

– Base classes need to share the static attributes– Use templates to get over that issue – One base class generated for each derived class– Use inheritance for the ‘Is-A’ relationship [Whenever the class ctor is called, the base class ctor is called, likewise for the dtor, increment and decrement operations happen automatically]

Page 24: C++ Basics

Page 24

Cost of runtime polymorphism• Each class that has a virtual method has an associated ‘vtable’• A ‘vtable’ is just an array of function pointers containing pointers to virtual method implementations for that class• Each object of any such class, has a pointer to the associated vtable• The compiler creates the required vtables and initializes each object to point to the associated vtable all ‘Under the hood’

Page 25: C++ Basics

Page 25

What happens at runtime?• The compiler would have converted all your virtual method calls

– Your call: pDerived->func2();– It’s become: (*pDerived->vptr[1])(pDerived)

• As we see above, the vptr stored by the compiler in the derived object is looked up, an offset (+1) added to get to the second virtual method in the class, and the function is called Runtime.

Page 26: C++ Basics

Page 26

So, what’s the cost?• Direct cost – vtable lookup (Put at about 5-10% overhead as opposed to non-virtual methods)• Indirect cost –

– Cannot inline virtual methods (Makes a big difference)– Each objects needs to store extra pointer (An issue for fine grained objects – say 1000000 link element objects, each containing 4 bytes extra!)

Page 27: C++ Basics

Page 27

Is that all? • Well, this gets worse when MI (Multiple Inheritance is used)• Now, the deal is 15-20% overhead for MI for method defined in the 2nd and onwards base class. There’s no penalty for methods in the first base class we derive from• Ensure your most frequently called methods are from the FIRST base class you derive from if you use MI, order your base classes accordingly

Page 28: C++ Basics

Page 28

Cost of compile time polymorphism• ZERO runtime cost (Abstraction without abstraction penalty) • However …

– Coders not aware of how templates work ‘Under the hood’ end up creating code bloat – Developer turn around time increased due to longer compiles (This could be avoided too)

Page 29: C++ Basics

Page 29

Template code bloat• Code bloat happens because compilers cannot do ‘Commonality and variability analysis’• If the code body is the same for a set of template argument values, the compiler fails to see that and generates multiple classes for each argument value• Eg: list<int *>, list<char *, list<MyClass*> all of these may have the same underlying implementation of a ‘Container of POINTERS’, but the compiler generates 3 different class definitions for these

Page 30: C++ Basics

Page 30

Template code bloat (Contd)• A coder who knows this, does the following

– Give a partial template specialization for POINTER types– Have that derive from a void * based container which has most of the implementation in it– This specialized class will have simple inline methods that ‘Delegate’ to the base class and gets work done

Page 31: C++ Basics

Page 31

Template code bloat (Contd)• So, we get the following result –

– The thin inline wrappers in the specialized class offer type safety– Majority of the code body is in the non-template base class and hence no duplication of it– The thin wrappers are all inline hence no performance overhead as well

• This is called the ‘Hoisting idiom’

Page 32: C++ Basics

Page 32

Longer compilation time• Happens mainly because the template method definitions have to be in the header file• They may in turn pull in other headers and hence lead to large include sizes and hence more compile time• More work to the compiler in case one uses template meta-programming

Page 33: C++ Basics

Page 33

Workaround• To reduce compile times, we can use the ‘Explicit instantiation’ technique in cases where large includes are warranted• Here basically you give the method body in a .cpp file and put only the template class definition in the .h file, but explicitly instantiate the template in the .cpp file where the methods are defined for all types expected

Page 34: C++ Basics

Page 34

Summary• Prefer inheritance when

– You want to reuse code/structure from the base class– You want to develop OO frameworks which need to store heterogeneous elements in their data structures

• Prefer templates when– You want generic data structures and algorithms– Where Speed is important

Page 35: C++ Basics

Page 35

Encapsulation in C++

Page 36: C++ Basics

Page 36

• Encapsulation Requires that functions, modules and classes:– Have clearly defined external interfaces– Hide implementation details

• Encapsulation is all about coupling – coupling happens through interfaces.• Exactly what is an interface?

Encapsulation

private data

private functions

public functions

Page 37: C++ Basics

Page 37

• Functions have four ways to interact with the external world:– Parameter list – local coupling:

• Value parameters and const references are input only– Functions with these parameters don’t have parametric side-affects.

• Non-const reference paramters and pointers are both input and output– We say that a function with non-const reference parameters has side-affects.

– Returned items – local coupling:• Return by value has no after-affects inside the function.• Return by reference can change the state of an object to which the function belongs.

– Global data – remote coupling:• Functions that use global data create remote and untrace-able side effects.

– Static local data – temporal coupling:• An invocation affects later invocations.

• The strongest encapsulation is with only pass-by-value or constant reference in and out.• However, the indirection allowed by non-constant references is just too powerful. We can’t live without it.• We can, and should, live without global data and we should minimize the use of static local data.

Function Interfaces

Page 38: C++ Basics

Page 38

• Prefer returning C++ references over pointers.– References provide access to objects. You only get to use the object’s interface with a

reference.– Pointers provide access to memory. Their proper use demands that the client understand

the design of the function, and perhaps the class:• Does the pointer point to an object or an array of objects?• Does it point to the heap or some other persistant object?• Whose responsibility is destruction?

• This is not a manifesto to eliminate all pointer use!– Pointers do a great job of capturing relationships:

• Arrays, Graphs, trees, lists, repositories• Their big brothers, iterators, are an essential part of the STL

– It is appropriate to return them from creational functions that act like sophisticated new calls.

C++ References versus Pointers

Page 39: C++ Basics

Page 39

• All the same issues hold for classes, via the member functions they provide.• Classes also support three accessibility levels: public, protected, and private.

– Public members define the client interface and should be immutable – changing the interface breaks client designs.

– Protected members define an interface for derived classes only. They also should be immutable once some of the derived classes are no longer under your control.

– Private members consist of all those helper functions that manage the class’s internal state.• For proper class encapsulation:

– Don’t use public or global data– Encapsulate member functions well, as discussed in earlier slides.– Decide carefully which functions will be public, protected, and private.– Never make member data public.

Classes

Page 40: C++ Basics

Page 40

• Constructors and destructors– Objects are created from a class pattern only by calling a constructor.– Whenever the thread of execution leaves a scope, all objects created

in that scope are destroyed. Part of that destruction is the execution of the objects’ destructor and the destructors of all its parts.

– A constructor’s job is to allocate whatever resources the class needs on startup.

– The destructor returns any allocated resources.– These actions mean that the class encapsulates its own resource

management. That is a very big deal!

Role of Constructors and Destructor

Page 41: C++ Basics

Page 41

• Composition is the best encapsulated relationship:– Only member functions of the class have access to the interface of private data member

objects.– Only member functions of the class and its derived classes have access to the interface of

a protected data member object.• Inheritance gives derived classes access to the protected data members of the

base class.– Behavior of a correct base class can be made incorrect by incorrect derived class objects.

• Using relationships may badly break encapsulation.– If you pass an object of a class to a member function of an object of the same class, the

receiving object has access to all the used object’s private and protected state.– Friend relationships extend this behavior to objects of other classes.

Class Relationships

Page 42: C++ Basics

Page 42

• What makes a design bad? Robert Martin suggests[1]:– Rigidity

It is hard to change because every change affects too many other parts of the system.

– FragilityWhen you make a change, unexpected parts of the system break.

– ImmobilityIt is hard to reuse a part of the existing software in another application because it cannot be disentangled from the current application.

• Many of these “Bad Design” issues stem very directly from poor encapsulation.

Bad Designs

Page 43: C++ Basics

Page 43

• The C++ object model has the source text of a user of an object responsible for carrying the object’s type information by including a header file.– If class A refers to class B, then A must include B’s header.– This is the way a C++ compiler does static type checking.– Remember, in contrast, that C# carries its type information in the assembly

metadata of the object itself.• A direct consequence of this fact is that, unless we do something special to

prevent it, the client is welded to specific versions of the objects it uses.– If the object changes anything in its class declaration, adding a new member

datum, for example, then the client has to acquire its new header and recompile.

C++ Class Encapsulation Problem

Page 44: C++ Basics

Page 44

• The something special we do is to:– Program to an Interface not an Implementation– Use an Object Factory to create the object.

• Here, interface means more than the public interface of a class.– An interface is an abstract base class, often a struct actually, containing at least one pure

virtual function.– It usually has no constructors and no data.– It has a destructor, only to qualify it as virtual.– It often has a static factory function so the client does not have to directly instantiate an

object of the class it represents.

• This interface shields its clients from all of the implementation details of the class it represents.

Programming to Interfaces

Page 45: C++ Basics

Page 45

• Designing to Interfaces and using factory functions completely eliminates the coupling of client to the implementation of its serving objects.

• Here is an example, that may be of other interest as well:

– Interfaces

Fini

Page 46: C++ Basics

Page 46

Thank You

For Your Kind cooperation


Recommended