389
C++ Horizon 1 Day No Topics to be covered Day#1 Basic concepts of OOPS, class and object definition Naming conventions Inline functions Scope resolution operator Default arguments Function overloading Constructors and Destructors Static members Type conversions Friends

Cpp final

  • Upload
    shaan

  • View
    217

  • Download
    3

Embed Size (px)

DESCRIPTION

C++ Presentation

Citation preview

  • C++Horizon*

  • C++Horizon*

  • C++Horizon*

  • C++Horizon*Concepts of OOPS

  • C++Horizon*A PIEAbstraction :The ability for a program to ignore some aspects of the information that it is manipulating, i.e. the ability to focus on the essential. It is the process of creating a category ( class ) by identifying those features of the category which give a nearly complete picture of the class as is required by the programmer.

    Encapsulation :It is the process of encapsulating all the identified data and functional properties for the category as a single entity, called class.It ensures that users of an object cannot change the internal state of the object in unexpected ways; only the object's own internal methods are allowed to access its state. Each object exposes an interface that specifies how other objects may interact with it.

  • C++Horizon*Polymorphism :It gives the ability to take more than one forms. That is, an operation may exhibit different behavior in different instances.Object-oriented languages can make message sends; the specific method which responds to a message send depends on what specific object the message is sent to. This gains polymorphism, because a single variable in the program text can hold different kinds of objects as the program runs, and thus the same program text can invoke different methods at different times in the same execution.

    Inheritance :It is the process by which an object of a particular category acquires the properties of another category thus generating a hierarchical classification of objects.It organizes and facilitates polymorphism and encapsulation by permitting objects to be defined and created that are specialized types of already-existing objects - these can share (and extend) their behavior without having to reimplement that behavior.

  • C++Horizon*OBJECTS AND CLASSESObjects :An object is a software bundle of related variables and methods.Real world objects share two characteristics: they all have state and behavior.Example :Dogs have state (name, color, breed, hungry) and behavior (barking, fetching, and wagging tail).Bicycles have state (current gear, current pedal cadence, two wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears).Software objects are modeled after real-world objects - they too have state and behavior.A software object maintains its state in one or more variables - an item of data named by an identifier.A software object implements its behavior with methods - a function (subroutine) associated with an object.

  • C++Horizon*The object's variables make up the center, or nucleus, of the object. Methods surround and hide the object's nucleus from other objects in the program.

    Packaging an object's variables within the protective custody of its methods is called encapsulation

    This conceptual picture of an object a nucleus of variables packaged within a protective membrane of methods is an ideal representation of an object and is the ideal that designers of object-oriented systems strive for.

    Often an object may wish to expose some of its variables or hide some of its methods. An object can specify one of four access levels for each of its variables and methods. The access level determines which other objects and classes can access that variable or method.

  • C++Horizon*Encapsulating related variables and methods into a neat software bundle is a simple yet powerful idea that provides two primary benefits :

    Modularity: The source code for an object can be written and maintained independently of the source code for other objects. Also, an object can be easily passed around in the system.You can give your bicycle to someone else, and it will still work.

    Information hiding: An object has a public interface that other objects can use to communicate with it. The object can maintain private information and methods that can be changed at any time without affecting the other objects that depend on it.You don't need to understand the gear mechanism on your bike to use it.

  • C++Horizon*Classes :A class is a blueprint or prototype that defines the variables and the methods common to all objects of a certain kind. In the real world, you often have many objects of the same kind. For example, your bicycle is just one of many bicycles in the world. Using object-oriented terminology, we say that your bicycle object is an instance of the class of objects known as bicycles. Bicycles have some state (current gear, current cadence, two wheels) and behavior (change gears, brake) in common. However, each bicycle's state is independent of and can be different from that of other bicycles.When building bicycles, manufacturers take advantage of the fact that bicycles share characteristics, building many bicycles from the same blueprint. It would be very inefficient to produce a new blueprint for every individual bicycle manufactured. In object-oriented software, it's also possible to have many objects of the same kind that share characteristics: rectangles, employee records, video clips, and so on. Like the bicycle manufacturers, you can take advantage of the fact that objects of the same kind are similar and you can create a blueprint for those objects.A software blueprint for objects is called a class.

  • C++Horizon*RULES OF THUMB for class designingIf you can think of it as a separate idea, make it a class.

    If you can think of it as a separate entity, make it an object of some class.

    If two classes have something significant in common, make that commonality a base class.

  • C++Horizon*MESSAGESAn object is a software bundle of related variables and methods.

    Software objects interact and communicate with each other using messages.

    A single object alone is generally not very useful. Instead, an object usually appears as a component of a larger program or application that contains many other objects.Your bicycle hanging from a hook in the garage is just a bunch of metal and rubber; by itself, the bicycle is incapable of any activity. The bicycle is useful only when another object (you) interacts with it (pedal).

    Software objects interact and communicate with each other by sending messages to each other. When object A wants object B to perform one of B's methods, object A sends a message to object B.

  • C++Horizon*Sometimes, the receiving object needs more information so that it knows exactly what to do; for example, when you want to change gears on your bicycle, you have to indicate which gear you want.This information is passed along with the message as parameters.

    A message has three parts :The object to which the message is addressedThe name of the method to performAny parameters needed by the method

    An object's behavior is expressed through its methods, so (aside from direct variable access) message passing supports all possible interactions between objects.

    Messages provide important benefits - Objects don't need to be in the same process or even on the same machine to send and receive messages back and forth to each other.

  • C++Horizon*OOAD

  • C++Horizon*The starting point for object-oriented analysis is to identify candidate objects and their relationships. In fact, this is the be-all and end-all of object-oriented analysis.

    The first stage can be a simple brain-storming of the possible objects. One method is to go through all the nouns in any documentation about the world you are analyzing, and considering these as candidate objects.Let us suppose that we are analyzing a system for a motor museum. The system is to produce a multi-media guide to the museum.

    A preliminary list of objects might be: car, bus, vehicle, number plate, exhibit, manufacturer, date of manufacture, value, position, weight, size, photograph, tools, shop, garage, ticket, owner, history

  • C++Horizon*Removing synonyms and/or generalizingThe first stage is to try and group together items which are either just different names for the same thing, or whether there is a common generalization. The obvious thing above is to examine the following group :car, bus, vehicle, number plate, exhibit, photograph, tools, garage

    It would seem that these could all be grouped together under the object exhibit. In the museum the behavior of cars, photographs, and garages are not radically different, so we can group them together. We can differentiate between the individual objects on the basis of an attribute, say type.

    We are then left with the list of candidate objects: exhibit, manufacturer, date of manufacture, value, position, weight, size, shop, ticket, owner, history

  • C++Horizon*Look for attributesAttributes are themselves objects, but with trivial behavior - essentially all you do is record their value. Considering the above list, the following are probably attributes of exhibit: date of manufacture, value, position, weight, size, owner

    And we are left with the candidate objects: exhibit, manufacturer, shop, ticket, history

    We might have considered manufacturer as an attribute, but it may be useful to separate out manufacturer information later in the design. So we keep it for the time-being. The time to fold it in as an attribute is when we find it has no discernible behavior of its own.

  • C++Horizon*Irrelevant objectsSometimes an object is irrelevant.Here the ticket object may be very relevant for a sales desk system, but not for a multi-media system. Likewise, the shop is irrelevant.

    So we strike these out and we are left with the following objects. exhibit, manufacturer, history

    We have these objects potentially linked in the following way.

  • C++Horizon*The process of developmentThe approach to development recommended here is an iterative one. It involves repeated refinement of the object model. The process needs to be controlled by an appropriate project management process, involving reviews and check pointing.

  • C++Horizon*Naming ConventionThis is a set of rules for choosing the character sequence to be used for identifiers which denote variables, types and functions etc. in source code and documentation.

    The reasons for using a naming convention (as opposed to allowing programmers to choose any character sequence) include the following :to reduce the effort needed to read and understand source codeto enhance source code appearance (for example, by disallowing overly long names or abbreviations)

  • C++Horizon*Some of the potential benefits that can be obtained by adopting a naming convention include the following :

    to provide additional information about the use to which an identifier is put

    to help promote consistency within a development team

    to enhance clarity in cases of potential ambiguity;

    to enhance the aesthetic and professional appearance of work product (for example, by disallowing overly long names, comical or "cute" names, or abbreviations);

    to provide meaningful data to be used in project handovers which require submission of program source code and all relevant documentation and

    to provide better understanding in case of code reuse after a long interval of time - well-chosen identifiers make it significantly easier for subsequent generations of analysts and developers to understand what the system is doing and how to fix or extend the source code for new business needs.

  • C++Horizon*The two most common conventions are :

    The CamelCase notation (originally known as medial capitals)

    The Hungarian Notation (which encodes either the purpose - "Apps Hungarian, or the type - "Systems Hungarian" of a variable in its name.)

  • C++Horizon*The CamelCase :This is the practice of writing compound words or phrases in which the elements are joined without spaces, with each element's initial letter capitalized within the compound and the first letter is either upper or lower case - as in "LaBelle", BackColor or "iPod".The name comes from the uppercase "bumps" in the middle of the compound word, suggestive of the humps of a camel.The practice is known by many other names. In computer programming, it is called Pascal case if the first letter is capitalized, and camel case otherwise.The first letter of a camel-case compound may or may not be capitalized.Camel case is by no means universal in computing. In some programming languages, notably Lisp and Forth, compound names are usually separated by hyphens.The use of medial caps for compound identifiers is recommended by the coding style guidelines of many organizations or software projects.For some languages (such as Mesa, Pascal, Modula, Java and Microsoft's .NET) this practice is recommended by the language developers or by authoritative manuals and has therefore become part of the language's "culture".

  • C++Horizon*The Hungarian Notation (original developer, Charles Simonyi) :Hungarian notation is an identifier naming convention in which the name of a variable or function indicates its type or intended use.

    There are two types of Hungarian notation :Systems Hungarian notationandApps Hungarian notation.

    The two notations differ is in the purpose of the prefixes.

    Hungarian notation was designed to be language-independent, and found its first major use with the BCPL programming language.

    In Hungarian notation, a variable name starts with a group of lower-case letters which are mnemonics for the type or purpose of that variable, followed by whatever name the programmer has chosen

    The first character of the given name can be capitalised to separate it from the type indicators (as in CamelCase). Otherwise the case of this character denotes scope.

  • C++Horizon*The Systems Hungarian Notation :In Systems Hungarian notation, the prefix encodes the actual data type of the variable. For example:lAccountNum : variable is a long integer ("l")arru8NumberList : variable is an array of unsigned 8-bit integers ("arru8")szName : variable is a zero-terminated string ("sz")bReadLine(bPort,&arru8NumberList) : function with a byte-value return code.

    The Apps Hungarian Notation :Apps Hungarian notation does not encode the actual data type, but rather, it gives a hint as to what the variable's purpose is, or what it represents.rwPosition : variable represents a row ("rw")usName : variable represents an unsafe string ("us"), which needs to be "sanitized" before it is usedstrName : Variable represents a string ("str") containing the name, but does not specify how that string is implemented

    It is possible for code using Apps Hungarian notation to sometimes contain Systems Hungarian when describing variables that are defined solely in terms of their type.

  • C++Horizon*The Hungarian notation always uses initial lower-case letters as mnemonics.

    It does not prescribe the mnemonics themselves. There are several widely used conventions, but any set of letters can be used, as long as they are consistent within a given body of code.

    Some of the suggested prefixes are :pX is a pointer to another type X; this contains very little semantic information. d is a prefix meaning difference between two values; for instance, dY might represent a distance along the Y-axis of a graph, while a variable just called y might be an absolute position. This is entirely semantic in nature.sz is a null or zero-terminated string. In C, this contains some semantic information because it's not clear whether a variable of type char* is a pointer to a single character, an array of characters or a zero-terminated string. w marks a variable that is a word. This contains essentially no semantic information at all.b marks a byte, which in contrast to w might have semantic information, because in C the only byte-sized data type is the char, so these are sometimes used to hold numeric values.

  • C++Horizon*The Rules :This list of rules is comprehensive, and thus covers both common and rare situations.

    VariablesAll variable names are composed of four elements: scope, prefixes, base type, and qualifiers.Not all elements are present in all variable names; the only part that is always present is the base type.Base TypesThe base type should not be confused with the types supported directly by the programming language; most base types are application specific (and are based on structures, classes, enumerated values, etc, that are created for that application).Tags should be short (typically two or three letters) and somewhat mnemonic.Because of the brevity, the mnemonic value will be useful only as a reminder to someone who knows the application, and has been told what the basic types are; the name will not be sufficient to inform (by itself) a casual viewer what is being referred to.It is essential that all tags used in a given application be clearly documented. This is extremely useful in helping a new programmer learn the code.

  • C++Horizon*There are a few standard types that appear in many different applications :fa flag (boolean, logical)ch a character. sza zero-terminated string. This is the way strings are represented in C/C++. fna function. Since about the only thing you can do with a function is take its address, this almost always has a "p" prefix.

    There are some more types that appear in many applications : ba byte (8 bits).wan int (as defined by the C/C++ compiler -- it does not imply a specific size).swa short word (16 bits).lwa long word (32 bits).llwa long long word (64-bits).

  • C++Horizon*PrefixesThe standard prefixes are: pa pointer. For example, a pch is a pointer to a character. aan array. For example, an ach is an array of characters.Ian index into an array. For example, an ich is used to index an ach (with a ch as the result, i.e. ch = ach[ich]). ca count.da difference between two instances of a type.gra group, usually of variable-size objects.ean element of an array.ua union. This is a rarely used prefix; it is used for variables that can hold one of several types.wa wide value. This is used in conjunction with ch and sz for double-byte charactersuan unsigned value. Typically used as a prefix to w, lw, and sw.

  • C++Horizon*QualifiersThe standard qualifiers are:Minthe first element in a set. This is very similar to First, but typically refers to the actual first element of an array, not just the first to be dealt with.Maxthe upper limit of elements in a set.Mostthe current last element in a set.Firstthe first element (in a set) to be dealt with.Lastthe last element (in a set) to be dealt with.

    ScopeMost variables are used within the scope of a function. For those that have a broader scope, one of the following scopes is placed at the beginning of the variable name (before any prefixes) :m_a member of a class. This is used to label the variables (but not methods) in a class. This is used so that member variables can be easily distinguished from local variables in the class methods. g_a global. This is applied to variables that are available to numerous functions in multiple files. s_a static. This is applied to variables that are available to multiple functions all within the same file, but not available to functions in other files (essentially a global variable, but private to one file).

  • C++Horizon*FunctionsThe above rules used for variable names do not work as well for functions.

    Whereas the type of a variable is always quite important, specifying how that variable may be used, the important part of a function is typically what it does.

    In addition, the context for functions is usually the entire program, so there is more chance for conflict.

    Some rules for functions are as follows :All function names are distinguished from variable names by the use of some standard punctuation; in C/C++ this is done by capitalizing the first letter of the function name (all variable names begin with a lowercase type).If the function returns a value, its name begins with the type of the value returned; if no value is returned, the name must not begin with a valid type. If the function does more than just determine a return value based on its parameters, follow the return type (if any) with a few words describing what the function does (a verb followed by an object is usually good). Each word should be capitalized.If the function is defined as static (it can be called only from functions within its file), an underscore (_) should be placed at the beginning of the name.

  • C++Horizon*C++

  • C++Horizon*A Sample C++ Program#include using namespace std ;

    int main( ){cout

  • C++Horizon*Structure of C++ ProgramThe code is organized as follows :The class declarations are placed in a header file.

    The definitions of member functions go in another file.

    The main program is placed in the third file which includes the other two files as it will be using the classes created in those files.

  • C++Horizon*Generating the ExecutableThe following command compiles and links a program to generate an executable :c++ try.cThis command generates a file called a.out which is an executable file.

    The following only compiles the program file to generate an object file :c++ -c try.cThis generates a file try.o which is the object file corresponding to the program file try.c.

    This object file can then be linked by the c++ command to get the executable file a.out.

  • C++Horizon*The default executable produced by c++ is a.out as the executable. But the executable name can be changed by using the o flag with c++

    c++ try.o -o try.exec++ try.c -o try.exe

    This command produces try.exe as the executable file.

  • C++Horizon*Data Types and Control StructuresData Types :The data types are the same as in C.

    There is a new kind of variable that is introduced in C++. It is the reference variable.

    Example :inti = 10 ;int& x = i ;x = 20 ;cout

  • C++Horizon*A reference variable :is another name for an already created variablemust be initialized at the time of declarationcan be created for built in as well as user defined data typesReferences are compiled as pointers which are implicitly dereferenced at each use involve hidden dereference operations that are costlyApplication of reference variables in argument passing :void f(int &i){ i += 10 ;}

    main( ){intk = 12 ;f(k) ;cout

  • C++Horizon*Using the const qualifier :If a function argument is declared as const then that argument can not be modified within the function. Else a compiler error is generated.Example :void func( const int &x, int y) {x = 10 ; // generates an errory += x ; }

    constant pointer (must be initialized during declaration) : char * const ptr1 = HELLO ;// the address in ptr1 can not be modified henceforth

    pointer to a constant :int const * ptr2 = &m ;//here int and const can be interchanged without causing any effect// ptr2 can point to any variable of matching type, but the contents of what it points to can not be changed.i.e., following statement is illegal :ptr1 = new char[10] ;i.e., following is illegal :*ptr2 = 80 ;And following is legal :ptr2 = &k ;

  • C++Horizon*The following code depicts the difference between a 'constant pointer' and 'pointer to a constant' :

    main() { int x = 10, y = 9 ; int *const p1 = &x ; int const *p2 = &x ;

    *p1 = 77 ; *p2 = 55 ;

    p1 = &y ; p2 = &y ;}

  • C++Horizon*A member function in a class can be declared as const as given below. In this case such a member function can not modify the object on which the function has been invoked.Example :class someclass {int datamem ;public :void memfunc (int y) const {datamem = y ; // generates an error}}

  • C++Horizon*LOOK AT THE FOLLOWING CODE IN STRAUSTRUP

    #include

    void f(char *ch) {cout

  • C++Horizon*Control Structures :These are the same as in C.

  • C++Horizon*Operators in C++All C operators are valid in C++. The additional new operators of C++ are listed below :>extraction operator ::scope resolution operator::*to declare pointer to class member->*to access class member using pointer to the object and pointer to that member.*to access class member using object name and pointer to that memberdeletememory release operatornewmemory allocation operator

  • C++Horizon*class X { public :int a ;void f(int b) { cout
  • C++Horizon*class temp {public : char *val ;void print(int x) { cout
  • C++Horizon*Associativity of OperatorsUnary operators and the assignment operators are right associative.Thus a = b = c means a = (b = c)AND* p++ means * ( p++ )

    The remaining operators are left associative.

    Thusa + b + c means (a + b) + ca + b * c means a + (b * c) [* has higher precedence than +]a + b c means (a + b) - c

  • C++Horizon*Inline FunctionsAn inline function is a function for which the function call is replaced by the complete function code by the compiler. (Similarity with the macros)

    Requirement for inline functions :There is a cost involved in function calls (jumping to the func, saving registers, pushing arguments to stack and returning back) that becomes appreciable for small functions. Inline functions overcome this overhead.

    It is different and far more superior than macros in the following respects :Inline functions are handled by the compiler while macros are handled by the pre processor.

    Macros do not undergo the usual error checking. This is not true for inline functions.

  • C++Horizon*If expressions are passed to macros then they are as is passed to the replaced code. In case of inline functions expressions passed as input arguments are first evaluated and then passed to the invoked function.Example :inline int sq(int a){return (a*a) ;}

    main( ){cout

  • C++Horizon*How to make a function inline ?By using the inline prefix to the function definition.

    The use of the inline keyword does not ensure that the function would definitely become inline. It is only a request to the compiler which may ignore the request in case of the following situations :the function is too longfor functions returning values if a loop, a switch or a goto existsfor functions not returning values if a return statement existsif functions contain static variablesif the function is recursive

    But inline functions make the program take up more memory because the statements of these functions are reproduced at each point the function is called.

  • C++Horizon*Class DefinitionA class can be seen as an extension of a structure with the following differences :A class by default provides the features of data hiding while a structure does not.

    By default the members of a class are private while those of a structure are public.

    A class data type is used to create a specific category encapsulating the data and the functional properties of the category.

  • C++Horizon*A sample declaration :class item{intnumber ;floatcost ;

    public :void getdata(int a, float b){//code for getdata}

    void dispdata( ){//code for dispdata}} ;

  • C++Horizon*In C++ we can declare variables of structures as follows :

    structmy_struct{//members of the structure} ;

    my_structs1, s2 ;

    Thus we do not need to use the keyword struct while declaring variables of the structure data type.

  • C++Horizon*Object CreationWhat is an object ?

    An object is an instance of a class just as a variable is an instance of a built-in data type or a user-defined structure.

    Object Creation :

    Objects for an existing class my_class can be declared as follows :my_classobj1 , obj2 ;

    Objects are also created by the use of the keyword new

  • C++Horizon*What happens when an object is created ?

    Objects are created statically in C++ through the above piece of code.

    For every object created, a unique block of memory is allocated for all the data members of the class.

    The member functions are loaded only once for the whole class.

    All the objects of a class share the same set of functions.

  • C++Horizon*member function#1member function#2COMMON FOR ALL OBJECTSOF THE SAME CLASSmemory created whenfunctions definedmemory created whenobjects definedObject #1Object #2Object #3member variable#1member variable#2member variable#3member variable#2member variable#3member variable#1member variable#1member variable#2member variable#3A UNIQUE SET PER OBJECT

  • C++Horizon*Member Access :For the item class declared earlier :

    main( ){itemi1 , i2 ;i1.getdata( 10 , 12.6 ) ;i2.getdata( 13 , 7.8 ) ;i1.dispdata( ) ;i2.dispdata( ) ;}

    The members of the class are accessed by using the dot operator on the class object just as in the case of a structure.

  • C++Horizon*Private members :The members declared in the private section of a class have the following properties :Their accessibility is limited within the class only.They are hidden for the outside world. Public members :The members declared in the public section of a class have the following properties :They can be accessed from any part of the code.Every class must contain at least one non private member.

  • C++Horizon*Example :For the item class declared earlier :

    main( ){itemi1 ;

    i1.number=10; //error:cant access private member outside class.i1.getdata(10,12.6); // public mems can be accessed outside classi1.dispdata( ) ;}

  • C++Horizon*Scope Resolution OperatorIt can be used to access a global variable from within an inner block even if the inner block tries to hide the global variableExample :intm = 10 ;main( ){int m = 20 ;{int m = 30 ;cout
  • C++Horizon*It is used for providing outside the class definition for member functions.Example :class item {intx , y ;public :void getdata(int a , int b) ;void dispdata( ) ;} ;

    void item :: getdata(int a , int b){// code for getdata}

    void item :: dispdata( ) {// code for dispdata}

  • C++Horizon*Default ArgumentsThis mechanism allows invocation of a function without specifying all the arguments.

    This is possible if the function has been declared with default arguments.Example :float amount ( float p, int time, float r = 0.15) ;

    Such a function can be invoked in either of the following ways :float val = amount(5000, 7) ;float val = amount(3000, 3, 0.18) ;

    In the first case the third argument takes the default value of 0.15

  • C++Horizon*Only trailing arguments can be assigned default values.

    A function can have any number of default values.

    They provide the flexibility to have scope for addition of new parameters to an existing function.

  • C++Horizon*Method OverloadingIt allows us to use the same name for different functions.It is generally used for functions with similar functionalities.It results in static polymorphism also known as early binding.The functions with the same name are identified on the basis of their unique input argument list.

    Example :Let there exist the following function declarations :int add(int a , int b , int c) ;int add(int a , int b) ;

    Let there be the following function calls :add(3 , 8) ;// invokes the second versionadd(1 , 2 , 3) ;// invokes the first version

  • C++Horizon*The function selection involves the following steps :The compiler first tries to find an exact match in which the types of actual arguments are the same and use that function.

    If an exact match is not found, the compiler uses the integral promotions to the actual arguments, example :char to intfloat to double

    When both the above fail, the compiler tries to use the built in conversions to the actual arguments and then uses the function whose match is unique. Example :int to doublederived* to base*

    Finally if nothing works, the compiler matches using user-defined conversions.

  • C++Horizon*If the conversion is possible to have multiple matches, then the compiler generates an error message.Example : DeclarationsFunction calllong sq(long n)sq(10) ;double sq(double x)This generates an error because int can be converted to both long as well as double.

    DeclarationsFunction callvoid f(int x, int y, int z = 80)f(2, 20)void f(int x, int y)f(3, 33, 333)The first call generates an error while the second call executes the first function.

  • C++Horizon*Overloading Member Functions from base and derived classesA member function named 'f' in a class A will hide all other members named 'f' in the base classes of A, regardless of return types or arguments.To overload, rather than hide, a function of a base class A in a derived class B, you introduce the name of the function into the scope of B with a using declaration.This is shown in the following code :class par { public : void f() {cout
  • C++Horizon*Constructors and DestructorsConstructors :are special functions

    have the same name as the class name

    are invoked automatically every time an object of an associated class is created.

    can not be invoked explicitly

    do not have a return type

    should not be declared in the private section of a class, else objects of that class can not be created[there should be at least one public constructor]

  • C++Horizon*can be overloaded

    can have default arguments

    can not be referenced by their addresses

    a constructor that takes no parameters is called the default constructor

    if there is no constructor within the class then and only then the compiler supplies with a default constructor

  • C++Horizon*Copy Constructor :It takes a reference of an object of the same class as itself as an argument.

    It creates a new object by initializing each member of the new object with the value of the corresponding member of the object passed as argument.

    When no copy constructor is defined within the class, the compiler supplies its own copy constructor.Example :class temp {public : temp( ) { cout

  • C++Horizon*The following code displays how a pass-by-value invokes the copy constructor :

    class temp {public : temp() {cout

  • C++Horizon*Destructors :are special functions like constructors

    have the same name as the class name preceded by a tilde

    can be invoked explicitly

    are invoked implicitly by the compiler upon exit from the program (or block or function); basically it is invoked when the object is no longer accessible

    can not return anything and has no return type

    can not take any input arguments overloaded destructors are not possible

    should not be declared in the private section of a class

  • C++Horizon*Destructors are not inherited.

    The body of a destructor is executed before the member objects.

    Destructors for nonstatic member objects are executed before the destructors for base classes.

    Member functions may be called from within a destructor.

    An object of a class with a constructor / destructor cannot be a member of a union.

    Destructors are invoked implicitly:when an auto or temporary object goes out of scopefor constructed static objects at program terminationthrough use of delete for objects created by new.

  • C++Horizon*Can be explicitly called as shown in the following code:

    class X { int x ; char ch ;public : X(){cout

  • C++Horizon*New and Delete OperatorsThese are used for dynamic allocation (new) and de-allocation (delete) of variables and objects.

    An object created by new is destroyed only when it is deleted.Example :class temp {public :temp( ) {cout

  • C++Horizon*Other Examples :The following creates an integer variable with initial value 12 ;int* p1 = new int (12) ;

    The following creates a memory space for an array of 10 integers :int*p2 = new int [10] ;

    Code :Output :class temp {CONSpublic :CONStemp( ) {CONS cout

  • C++Horizon*Following are the advantages of new over malloc :It automatically computes the size of the data object, the use of the sizeof operator is not required.

    It automatically returns the correct pointer type, no type casting is required.

    It is possible to initialize the object while creating the memory space.

    As the other operators, new and delete can also be overloaded.

    NEW RETURNS NULL POINTER IN CASE OF FAILURE.

  • C++Horizon*Stack and HeapThe memory that a program uses is typically divided into four different areas :The code area, where the program sits in the memoryThe data segment, where the global variables are storedThe heap, from where the dynamically allocated variables are allocatedThe stack, from where the parameters and the local variables are allocated

    The HeapThe heap (also known as the free store) is a large pool of memory used for dynamic allocation.In C++, when the new operator is used to allocate memory, this memory is assigned from the heap.Because the precise location of the memory allocated is not known in advance, the memory allocated has to be accessed indirectly which is why new returns a pointer.Sequential memory requests may not result in sequential memory addresses being allocated.When a dynamically allocated variable is deleted, the memory is returned to the heap and can then be reassigned as future allocation requests are received.

  • C++Horizon*The heap has advantages and disadvantages:1) Allocated memory stays allocated until it is specifically deallocated (beware memory leaks).2) Dynamically allocated memory must be accessed through a pointer.3) Because the heap is a big pool of memory, large arrays, structures, or classes should be allocated here.

    The StackA stack is a container that holds other variables (much like an array).However, whereas an array allows access and modification of elements in any order, a stack is more limited.The operations that can be performed on a stack are identical to the ones above:1) Look at the top item on the stack (usually done via a function called top())2) Take the top item off of the stack (done via a function called pop())3) Put a new item on top of the stack (done via a function called push())

    A stack is a last-in, first-out (LIFO) structure - the last item pushed onto the stack will be the first item popped off.

  • C++Horizon*The stack in actionThe sequence of steps that takes place when a function is called is as follows :The address of the instruction beyond the function call is pushed onto the stack. This is how the CPU remembers where to go after the function returns.

    Room is made on the stack for the functions return type. This is just a placeholder for now.

    The CPU jumps to the functions code.

    The current top of the stack is held in a special pointer called the stack frame. Everything added to the stack after this point is considered local to the function.

    All function arguments are placed on the stack.

    The instructions inside of the function begin executing.

    Local variables are pushed onto the stack as they are defined.

  • C++Horizon*When the function terminates, the following steps happen:The functions return value is copied into the placeholder that was put on the stack for this purpose.

    Everything after the stack frame pointer is popped off. This destroys all local variables and arguments.

    The return value is popped off the stack and is assigned as the value of the function. If the value of the function isnt assigned to anything, no assignment takes place, and the value is lost.

    The address of the next instruction to execute is popped off the stack, and the CPU resumes execution at that instruction.

    Stack overflowStack has a limited size, and can only hold a limited amount of information.If the program tries to put too much information on the stack, stack overflow will result.Stack overflow happens when all the memory in the stack has been allocated in that case, further allocations begin overflowing into other sections of memory.

  • C++Horizon*Stack overflow is generally the result of allocating too many variables on the stack, and/or making too many nested function calls (where function A calls function B calls function C calls function D etc)Overflowing the stack generally causes the program to crash.

    The stack has advantages and disadvantages:Memory allocated on the stack stays in scope as long as it is on the stack. It is destroyed when it is popped off the stack.

    Because the stack is relatively small, it is generally not a good idea to do anything that eats up lots of stack space. This includes allocating large arrays, structures, and classes, as well as heavy recursion.

  • Usage of typedefA typedef declaration introduces a name that, within its scope, becomes a synonym for the type given by the type-declaration portion of the declaration.

    This is done as follows :typedef type-declaration synonym; A typedef declaration can be used to construct shorter or more meaningful name for a type already defined by the language or for a user-defined type.

    In contrast to the class, struct, union, and enum declarations, typedef declarations do not introduce new types - they introduce new names for existing types.

    The typedef specifier can not be used inside a function definition.

    Typedef names share the name space with ordinary identifiers. Therefore, a program can have a typedef name and a local-scope identifier by the same name.

  • Any type can be declared with typedef, including pointer, function, and array types.

    A typedef name can be declared for a pointer to a structure or union type before the structure or union type is defined, as long as the definition has the same visibility as the declaration.

    Examples

    One use of typedef declarations is to make declarations more uniform and compact. For example:typedef char CHAR; // Character type.typedef CHAR * PSTR; // Pointer to a string (char *).PSTR strchr( PSTR source, CHAR target );typedef unsigned long ulong;ulong ul; // Equivalent to "unsigned long ul;"

    To use typedef to specify fundamental and derived types in the same declaration, declarators can be separated with commas. For example:typedef char CHAR, *PSTR;

  • The following example provides the type DRAWF for a function returning no value and taking two int arguments:void DRAWF( int, int );

    After the above typedef statement, the declarationDRAWF box;

    would be equivalent to the declaration void box( int, int );

    typedef is often combined with struct to declare and name user-defined types:typedef struct mystructtag { int i; double f;} mystruct;

    int main() { mystruct ms; ms.i = 10; ms.f = 0.99; printf("%d %f\n", ms.i, ms.f);}

  • C++Horizon*RecursionRecursion is when a function calls itself.Thus in the course of the function definition there is a call to that very same function. A check is made to see if a certain condition is true and in that case an exit (return from) from the recursive function is made.The case in which the recursion ends is called a base case.Additionally, just as in a loop, some value must change and we must incremently advance closer to our base case.

    Example :void myFunction( int counter) {if(counter == 0) return;else { cout

  • C++Horizon*Every recursion should have the following characteristics :A simple base case which we have a solution for and a return value. Sometimes there are more than one base cases. A way of getting our problem closer to the base case. I.e. a way to chop out part of the problem to get a somewhat simpler problem. A recursive call which passes the simpler problem back into the function.

    The key to thinking recursively is to see the solution to the problem as a smaller version of the same problem.

  • C Data StructuresHorizon*arguments received by the program that are given at the command line while starting a program

    in the following definition of main function :main( int argc, char ** argv)the command line arguments are received inside argc and argv as follows :argc : holds the number of parameters including the program name

    argv : is an array of stringseach string holds one argumentthe first string pointed by argv[0] is the program namethe remaining strings held in argv[1] to argv[argc 1] are the input arguments to the programCommand Line Arguments

  • C++Horizon*Static MembersSTATIC DATA MEMBERS :Static member variables have the following properties :It is initialized to 0 by default when it is created.

    Only one copy of a static data member is created per class.

    A static data member is shared by all the objects of the that class.A static member variable must be defined outside the class.Example :THIS DECLARATION CREATESclass temp {THE STATIC VARIABLEstatic int x ;} ;int temp :: x ;

  • C++Horizon*It can be accessed with the class name also.Example :temp::x = 19 ;

    Static variables are also known as class variables and are used to hold class wide information.

    They can be created with some initial value as shown below : class temp {static int x ;} ;int temp :: x = 17 ;

  • C++Horizon*STATIC MEMBER FUNCTIONS :

    Static member functions have the following properties :A static member function can access only the static members of the class.

    A static member function does not have a this pointer. So it can access nonstatic members of its class only by using . or -> operators.

    A static member function can not be virtual.

    There can not be a static and a nonstatic member function with the same name and the same arguments.

  • C++Horizon*They can be invoked by using the class name. They can also be invoked on an object of the class but still there behavior remains the same.Example :class temp {public :static void f( ) {cout
  • C++Horizon*For a local variable declared static in a member function :a static variable is available to the whole programthus, all instances of the type share the same copy of the static variable.Note : Assigning to a static local variable is not thread safe and is not recommended as a programming practice.Example :class C { public :void Test(int value) {static int var = 0;if (var == value) cout
  • C++Horizon*Create a class stack such that the stack is either for characters or for integers, the stack type being an input. Maximum number of items that the stack can hold should be defined by the user at the time of object creation. Test it by creating two objects one for integers and one for characters.

    Create a class complex which provides the following functions : add, subtract and multiply. Write only one add function through which you can add 2 or 3 or 4 complex numbers. These functions should return the complex number holding the result.Exercises

  • C++Horizon*Create a class hospital with the following data members : name, staffStrength, noOfPatients, areaCode. Let there be the following member functions of the class : patientAdmitted, patientReleased, staffResigns, staffJoins, displayInfo. Let there be a function which shows the total number of hospitals on the basis of the area code, assume that the area is divided into 3 area codes. Test the class by creating sufficient number of objects.

  • C++Horizon*Friend Functions and ClassesFriend functions are those functions which have access to the private and protected members of a class although they are themselves not members of the class.

    Example :class temp {inti ;public :temp( ) {i = 10 ;}friend void disp( temp t) ;} ;

    void disp( temp t) {cout

  • C++Horizon*Following are the special features of a friend function :It is not in the scope of the class to which it has been declared as a friend.

    It cannot access member names directly and can access the members only through an object of the class. That means the friend function accesses the members of a class for an object of that class.

    It can be declared as a friend either in the public or private section of the class, its meaning remaining the same.

    Friendship is not a symmetric relationship. It is neither inherited nor transitive.

    When a friend declaration refers to an overloaded name or operator, only the function specified by the argument types becomes the friend.

  • C++Horizon*Some Examples :Following code shows how an outside function is friendly to a class :class temp {inti ;public :temp( ) {i = 10 ;}friend void disp( temp t) ;} ;

    void disp( temp t) {cout

  • C++Horizon*Following code shows how a function of one class be friendly to a function of another class :class X {public :int f( ) { /* code */ }} ;

    class Y {friend int X::f( ) ;} ;

    If a class (X) declares another class (Y) as a friend class then all the members of the friend class (Y) can access all the members of the class X.Following code shows how a class can be declared as friendly :class X {friend class Y ;} ;

  • C++Horizon*Following code shows friendship is neither transitive nor inherited:class A {inta ;friend class B ;} ;class B {friend class C ;} ;class C {// NON TRANSITIVEpublic : void f(A *p) {p -> a++ ; }//error} ;class D : public B {// NON INHERITABLEpublic : void f(A *p) {p -> a++ ; }//error

    } ;

  • C++Horizon*Following code shows friend declaration referring to an overloaded name :class test {int i ;friend void f(test k) ;friend void f(test k, char c) ;public :test(){i = 10 ;}} ;

    void f(test i, char c) {cout

  • C++Horizon*Declaring a class to be a friend also implies that private and protected names from the class granting friendship can be used in the class receiving it. Example :class X {struct sx {} ;void f() {cout
  • C++Horizon*Operator OverloadingThis feature provides with the flexibility of creating new definition for most of the C++ operators.Following operators can not be overloaded :class member access operators ( . and .* )

    scope resolution operator ( :: )

    size operator ( sizeof )

    conditional operator ( ?: )

  • C++Horizon*Only the semantics of an operator can be modified, not its syntax.

    That is, the rules like the number of operands and precedencerules can not be modified.

    Operator overloading is achieved through the use of operator functions.Operator functions are either :non-static member functions orfriend functions

  • C++Horizon*OVERLOADING UNARY OPERATORS :Using Member Functions :class vector {intx1, x2, x3 ;public :vector( ) { x1 = 10 ; x2 = 20 ; x3 = 30 ; }void operator ( ) {x1 = -x2 ; x2 = -x3 ; x3 = -x1 ;}void disp( ) {cout
  • C++Horizon*Using Friend Function :class vector {intx1, x2, x3 ;public :vector( ) { x1 = 10 ; x2 = 20 ; x3 = 30 ; }friend void operator (vector &v ) ;void disp( ) {cout
  • C++Horizon*OVERLOADING BINARY OPERATORS :Using Member Functions :class vector {intx1, x2, x3 ;public :vector( int a, int b, int c) { x1 = a ; x2 = b ; x3 = c ; }vector operator +( vector v) {return vector (2*x1 + v.x1, 2*x2 + v.x2, 2*x3 + v.x3) ;}void disp( ) {cout
  • C++Horizon*Using Friend Function :class vector {intx1, x2, x3 ;public :vector( int a, int b, int c) { x1 = a ; x2 = b ; x3 = c ; }friend vector operator +( vector v, vector u) ;void disp( ) {cout
  • C++Horizon*Rules for overloading operators :Only existing operators can be overloaded.

    The overloaded operator must have at least one user defined type operand.

    The syntax rules of the original operators can not be changed.

    When using binary operators overloaded through a member function, the left hand operand must be an object of the relevant class.

    Binary arithmetic operators like +, -, *, / must explicitly return a value.

  • C++Horizon*OPERATORS THAT CANNOT BE OVERLOADED USING FRIENDS

    =Assignment operator( )Function call operator[ ]Subscripting operator->Class member access operator

    This is to ensure that their first operands are lvalues.{Friend functions can take variables, i.e., non-objects as first argument also. This should not happen for these overloaded operators.}

    [An lvalue is an expression referring to an object or function. Originally the term was used to mean something that can be on the left hand side of an assignment]

  • C++Horizon*WHY THE NEED FOR THE FRIEND FUNCTIONS FOR OPERATOR OVERLOADING

    Situations arise where a member function usage for operator overloading does not work.

    Eg :A = 2 + B // both A and B are objects.This can not be achieved through a member function because the left hand operand is responsible for invoking the member function.

    In this case the left hand operand is not an object. In case of friend function both the operands are passed as arguments. Hence it is not compulsory that the first argument has to be object.

  • C++Horizon*> operators :

    These can be overloaded using only friend functions.

    The left hand operands for these operators are cout and cin.

    These operands are system defined objects of the system defined classes istream and ostream.

    So a user can only create a friend function to overload these operators.

  • C++Horizon*class complex { private : int real, img ;public : complex() {}complex(int r, int i) {real = r; img = i ; }friend ostream & operator > (istream & s, complex & c) ; } ;

    ostream & operator

  • C++Horizon*The operator
  • C++Horizon*OVERLOADING THE SUBSCRIPT OPERATORSubscripting is considered a binary operator.The expression x [ y ] is interpreted as x.operator[ ] (y) where x is a class object.class vector {intarr[10] ;public : vector( ){for (int i = 0; i < 10; i++)arr[i] = i+1 ; }friend int operator +(vector v, int x) ;int operator [ ](int x){int temp = 1 ;for (int i = 0; i < x; i++)temp = temp * arr[i] ;return temp ;}} ;int operator +(vector v, int x){int temp = 1 ;for (int i = 0; i < x; i++)temp = temp * v.arr[i] ;return temp ;}main( ) {vectorv1 ;cout
  • C++Horizon*THE CLASS MEMBER ACCESS

    Class member access using -> is considered a unary operator.

    The expression x -> y is interpreted as (x.operator->())->y where x is a class object.

  • C++Horizon*THE INCREMENT AND DECREMENT OPERATORS

    The ++ and the -- operators can be overloaded as follows :In the prefix form :through a friend function:- takes one argument0

    through member function- takes no argument

    In the postfix form :through a friend function:- takes two arguments the second argument automatically passed as 0

    through member function- takes one argument

  • C++Horizon*class vector {intx1, x2, x3 ;public :vector( ) { x1 = 10 ; x2 = 20 ; x3 = 30 ; }//postfix formvoid operator ++(int i) {for(int cntr = 0; cntr < 2; cntr++) {x1++ ; x2++ ; x3++ ; } }//prefix formvoid operator ++( ){ x1++ ; x2++ ; x3++ ; }

    void disp( ) {cout

  • C++Horizon*class vector {intx1, x2, x3 ;public :vector( ){ x1 = 10 ; x2 = 20 ; x3 = 30 ; }friend void operator ++(vector &v, int j) ;friend void operator ++(vector &v) ;void disp( ) { cout
  • C++Horizon*

    class A {public :void operator () () {cout

  • C++Horizon*Create a class RationalNumber (fractions) with the following capabilities:Create a constructor that prevents a 0 denominator in a fraction, reduces or simplifies fractions that are not in reduced form and avoids negative denominators.Overload the addition, subtraction, multiplication and division operators for this class.Overload the relational and equality operators for this class.

    Develop a class Polynomial. The internal representation of a Polynomial is an array of terms. Each term contains a coefficient and an exponent. For example, the term 2x4 has the coefficient 2 and the exponent 4. Develop a complete class containing proper constructor and destructor functions as well as set and get functions. The class should also provide the following overloaded operator capabilities:Overload the addition operator (+) to add two Polynomials.Overload the subtraction operator (-) to subtract two Polynomials.Overload the assignment operator to assign one Polynomial to another.Overload the multiplication operator (*) to multiply two Polynomials.Overload the addition assignment operator (+=), subtraction assignment operator (-=), and multiplication assignment operator (*=).Exercises

  • C++Horizon*Shallow vs Deep copyingA shallow copy of an object copies all of the member field values.This works well if the fields are values, but may not be what is wanted for fields that point to dynamically allocated memory the pointer will be copied. but the memory it points to will not be copiedthe field in both the original object and the copy will then point to the same dynamically allocated memory, which is not usually what is wanted.The default copy constructor and assignment operator make shallow copies.

    A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields.To make a deep copy, a copy constructor must be written and the assignment operator overloaded, otherwise the copy will point to the original, with disastrous consequences.

  • C++Horizon*Thus :If an object has pointers to dynamically allocated memory,andthe dynamically allocated memory must be copied when the original object is copied,then a deep copy is required.

    A class that requires deep copies generally needs :A constructor to either make an initial allocation or set the pointer to NULL. A destructor to delete the dynamically allocated memory. A copy constructor to make a copy of the dynamically allocated memory. An overloaded assignment operator to make a copy of the dynamically allocated memory.

  • C++Horizon*Type ConversionsFollowing three types of conversions will be discussed :from built in type to class type

    from class type to built in type

    from one class type to another class type

  • C++Horizon*Built In Type to Class Type :The following statements are true under this situation :It is achieved through a constructor function.This constructor belongs to the destination class.

    Example :class integer {intval ;public :integer (int i) { val = i ;}integer(char *s) {val = strlen(s) ;}} ;

    main( ) {integer object(10) ;integer obj = 90 ;obj = 88 ;obj = abcd ;}

  • C++Horizon*Class Type to Built In Type :The following statements are true under this situation :It is achieved through a casting operator function.This casting operator function belongs to the source class.User-defined conversion cannot specify a return type

    Example :class vector {double x, y, z ;public :vector() {x = y = z = 9 ; }operator double() {// NOTE :: no return type specified.return (x+y+z) ; }} ;main( ) {vector v ;double l = v ; }

  • C++Horizon*Class Type to Another Class Type :The following statements are true under this situation :

    It can be achieved through :a casting operator function, in this case the function belongs to the source class

    a constructor function, in this case the constructor belongs to the destination class

  • C++Horizon*Example : c1 is source class and c2 is the destination class.The following code shows the usage of the casting operator function in the source class.class c2 ;class c1 {public :int i, j, k ;c1(int a, int b, int c) {i = a; j = b ;k = c ; }operator c2( ) {c2temp ;temp.x = i+j ; temp.y = k ; return temp ; }} ;The following code shows the usage of the constructor function in the destination class. class c2 {public :int x, y ;c2(c1 p) {x = p.i ; y = p.k ; }} ;

  • C++Horizon*class c2 ;class c1 {public :int i, j, k ;c1(int a, int b, int c) {i = a; j = b ;k = c ; }operator c2( ) ;} ;

    class c2 {public :int x, y ;c2() {x = 0; y = 0 ;}} ;

    c1 :: operator c2() {c2temp ;temp.x = i+j ; temp.y = k ; return temp ; }

    void main() {c1ob1(1, 2, 3) ;c2ob2(ob1) ;}casting operator func in the source classwith forward declaration

  • C++Horizon*class c1 ;class c2 {public :int x, y ;c2(c1 p) ;} ;

    class c1 {public :int i, j, k ;c1(int a, int b, int c) {i = a; j = b ;k = c ; }} ;

    c2 :: c2 (c1 p) {x = p.i ; y = p.k ; }

    void main() {c1ob1(1, 2, 3) ;c2ob2(ob1) ;}constructor func in the destination classwith forward declaration

  • C++Horizon*String objects are a special type of container, specifically designed to operate with sequences of characters.

    Unlike traditional c-strings, which are mere sequences of characters in a memory array, C++ string objects belong to a class with many built-in features to operate with strings in a more intuitive way and with some additional useful features common to C++ containers.

    The string class is an instantiation of the basic_string class template, defined in as:typedef basic_string string;

    The following example shows a simple usage of the class :#include #include using namespace std ;void main() {stringobj("hello") ;cout

  • C++Horizon*In the C++ programming language, the std::string class is a standard representation for a string of text.

    This class removes many of the problems introduced by C-style strings by putting the onus of memory ownership on the string class rather than on the programmer.

    The class provides some typical string operations like comparison, concatenation, find and replace, and a function for obtaining substrings.

    It can be constructed from a C-style string, and a C-style string can also be obtained from it.

    The main constructors provided by the class are :string ( );string ( const string& str );string ( const string& str, size_t pos, size_t n = npos );string ( const char * s, size_t n );string ( const char * s );string ( size_t n, char c );template string (InputIterator begin, InputIterator end);

  • C++Horizon*Some important member functions :lengthcapacityfindinsertappendc_strdatacomparesubstr

    The overloaded operators are :operator+=operator=operator[]

  • C++Horizon*#include #include using namespace std ;

    int main () { char * cstr, *p;

    string str ("Please split this phrase into tokens");

    cstr = new char [str.size()+1]; strcpy (cstr, str.c_str()); // cstr now contains a c-string copy of str

    p=strtok (cstr," "); while (p!=NULL) { cout

  • C++Horizon*#include #include using namespace std;

    int main () { string str("to be question"); string str2("the "); string str3("or not to be") ; string::iterator it;

    str.insert(6,str2); cout

  • C++Horizon*#include #include using namespace std;

    int main (){ string name ("John"); string family ("Smith"); name += " K. "; // c-string name += family; // string name += '\n'; // character

    cout

  • C++Horizon*Define a class vector to hold 10 integers. Overload the operators +, -, =, *. Overload the subscript operator [] to retrieve a specific integer from the vector.

    Define a class String which behaves as the char * string. Overload the following operators : + (to implement the string concatenation), *, ++ and the -- operators. Provide a constructor that creates a string of the specified size, in the absence of the specified size, some default size of 50 chars is taken.Exercises

  • C++Horizon*InheritanceA class inherits state and behavior from its superclass. Inheritance provides a powerful and natural mechanism for organizing and structuring software programs. Example : mountain bikes, road bikes, and tandems are all kinds of bicycles. In object-oriented terminology, mountain bikes, road bikes, and tandems are all subclasses of the bicycle class. Similarly, the bicycle class is the superclass of mountain bikes, road bikes, and tandems. Each subclass inherits state (in the form of variable declarations) from the superclass. Mountain bikes, road bikes, and tandems share some states: eg speed. Also, each subclass inherits methods from the superclass. Mountain bikes, road bikes, and tandems share some behaviors: braking and changing pedaling speed, for example.

  • C++Horizon*However, subclasses are not limited to the state and behaviors provided to them by their superclass. Subclasses can add variables and methods to the ones they inherit from the superclass. Tandem bicycles have two seats and two sets of handle bars; some mountain bikes have an additional chain ring, giving them a lower gear ratio. Subclasses can also override inherited methods and provide specialized implementations for those methods. For example, if you had a mountain bike with an additional chain ring, you would override the "change gears" method so that the rider could shift into those lower gears. You are not limited to just one layer of inheritance. The inheritance tree, or class hierarchy, can be as deep as needed. Methods and variables are inherited down through the levels. In general, the farther down in the hierarchy a class appears, the more specialized its behavior.

  • C++Horizon*Class hierarchies should reflect what the classes are, not how they're implemented. If we implemented a tricycle class, it might be convenient to make it a subclass of the bicycle class both tricycles and bicycles have a current speed and cadence but because a tricycle is not a bicycle, it's unwise to publicly tie the two classes together. It could confuse users, make the tricycle class have methods (such as "change gears") that it doesn't need, and make updating or improving the tricycle class difficult.

    Inheritance offers the following benefits:Subclasses provide specialized behaviors from the basis of common elements provided by the superclass. Through the use of inheritance, programmers can reuse the code in the superclass many times.

  • C++Horizon*Programmers can implement superclasses called abstract classes that define common behaviors. The abstract superclass defines and may partially implement the behavior, but much of the class is undefined and unimplemented. Other programmers fill in the details with specialized subclasses.

  • C++Horizon*Provides for the reusability of code

    One class can be derived from another

    The class that inherits from another is the derived class

    The class inherited from is the base class

    An object of newly derived class is also an object of the base class

  • C++Horizon*BDB1B2DBD1D2D3single inheritancemultiple inheritancehierarchical inheritanceDDBBDBD2BD1Bmultilevel inheritancehybrid inheritanceVarious Forms of Inheritance

  • C++Horizon*Example :class Base{int intVar;public:int i;void funcB(unsigned x) { /* code */ }} ;class Derived : public Base{public:void funcD(unsigned x) { /* code */ }// belongs to the derived class};Single Inheritance

  • C++Horizon*Member AccessibilityThe members of a class can have the following visibility modes :private :the default modevisibility limited within class only

    protected :visible within classvisible also within the subclass as private memberpublic :visible everywhere

    class X {private : //accessible to members and friends only

    protected ://accessible to members and friends and//to members and friends of derived classes onlypublic ://accessible to the general public} ;

  • C++Horizon*A derived class can be created by inheriting the base class in the following modes :Derivation ModesprivateprotectedpublicThe default mode of derivation is private.class der-class-name : visibility mode base-class-name{// mems of derived class}

  • C++Horizon*The following table shows the visibility of the inherited members depending on the derivation mode.

  • C++Horizon*Multiple InheritanceSyntax is as follows :

    class D : visibility B1, visibility B2, {// mems of D} ;

  • C++Horizon*Virtual Base ClassesFor the following example :B1B2DA1A2D inherits the properties from the following classes :B1B2A1 through B1A2 through B2

  • C++Horizon*parent#1parent#2DIn case B1 and B2 have the same parent as shown in the following figure :grand parentD1 inherits the properties of class grandparent through parent#1 as well as parent#2.This is an ambiguous situation.

  • C++Horizon*class G {public :inti ;} ;class P1:public G {} ;class P2:public G {} ;class D: public P1, public P2 {} ;

    main(){D d1 ;cout

  • C++Horizon*It is essential to declare the common base class as a virtual base class as shown below :

    class G {// mems of G} ;

    class P1: virtual public G {} ;

    class P2: public virtual G {} ;

    class D: public P1, public P2 {} ;

    This ensures that only one copy of the parent class G is available in D.

  • C++Horizon*Constructors In Derived ClassesAs long as no base class constructor takes an argument, the derived class need not have a constructor function.

    If the base class contains at least one constructor with at least one argument then it is compulsory for the derived class to have a constructor and pass arguments to base class constructors.

    When an object of derived class is created the base constructor is executed before the derived constructor.

    Example :class D : public A {} ;constructor execution order : A, D

  • C++Horizon*In multiple inheritance, the base class constructors are executed in the order in which the base classes appear in the declaration of the derived class.Example :class D : public A1, public A2, public A3 {} ;constructor execution order : A1, A2, A3, D

    In case of multilevel inheritance the constructors are executed in the order of inheritance.

    Example :class B : public A {} ;class D : public B {} ; constructor execution order : A, B, D

  • C++Horizon*The constructors of virtual base classes are invoked before any non virtual base class constructors.Example :class D : public A, virtual public B {} ;execution order : B, A, D

    The derived class must pass the initial values to the base class constructors.

    It does so for only its immediate parents.

    The derived class constructors receive the entire list of arguments and pass them to the base constructors in the order in which they are declared in the base class.

  • C++Horizon*Example :class B1 {inti1, j1 ;public :B1(int x, int y) {i1 = x, j1 = y ;cout
  • C++Horizon*class D : public B1, public B2 {public :D(int a, int b, int c):B2(c, a), B1(b, c){cout
  • C++Horizon*class gp { public : gp(int a, int b) {cout
  • C++Horizon*Hence :

    First, virtual base classes are created before non-virtual base classes, which ensures all bases get created before their derived classes.

    Second, note that the p1 and p2 constructors still have calls to the gp constructor. If we are creating an instance of ch, these constructor calls are simply ignored because ch is responsible for creating the gp, not p1 or p2.

    However, if we were to create an instance of p1 or p2, the virtual keyword is ignored, those constructor calls would be used, and normal inheritance rules apply.

    Third, if a class inherits one or more classes that have virtual parents, the most derived class is responsible for constructing the virtual base class. In this case, ch (or gc) inherits p1 and p2, both of which have a gp virtual base class. ch (or gc) , the most derived class, is responsible for creation of gp.

  • C++Horizon*Initialization List in the Constructor Function :Example :class XYZ {int a ;int b ;public :XYZ(int i, int j) : a(i), b(2+j){ }XYZ(int i) : b ( a+1 ) , a ( 3*i ) { }} ;main( ) {XYZ obj1(2, 3) ;XYZobj2(6) ;}

    This assigns the value 2 to a and 5 to b for obj1 and 18 to a and 19 to b for obj2.a can not be given in terms of b because data members are initialized in the order in which they are created which is the same as the order in which they are declared.

  • C++Horizon*An object can be a collection of many other objects.

    Thus members of a class can be objects of some other classes.Containing ClassesFollowing are the differences between Inheritance and Containership :Inheritance :provides the is a relationship between the related classesderived class object is an extended base class objectContainership :provides the has a relationship between the related classescontainer class object has a property displayed by the contained class.

  • C++Horizon*Constructor Invocation Rules for Container ClassesFirst all those member are created which are themselves objects of other class.

    The ordinary members are created afterwards.

    Constructors of the member objects are executed before the class constructor.They are executed in the same order as the order in which they are declared.

    The arguments to the member objects constructor are passed by the main class constructor just as in the case of inheritance.

  • C++Horizon*class mem {inti_mem ; charc_mem ;public :mem(int i, char c) : i_mem(i), c_mem(c) {cout
  • C++Horizon*Destructor Invocation RulesThe order of destruction is just the reverse of the order of construction, i.e., the first constructed is the last destroyed.

  • C++Horizon*Final class in C++ Class which Can't be inherited by other class, that class is called final class.In C++ final class has to be logically created.This can be done in two ways :Object of the final class will be on heap class final2{public: static final2* Create() { return (new final2()) ; }static void Des(final2 *p) {delete p ;}private: ~final2() {} };int main() { final2 *f ; f = final2::Create() ; // Object only on Heap final2::Des(f) ;}class child : public final2 {public: child(){ }} ;//Error will come because child class can not inherit final2 class - destructor of the final2 class is private.

  • C++Horizon*Object of the final class will be on stack class temp{private: ~temp( ) {cout
  • C++Horizon*PointersPointers to objects can be declared and initialized in just the same way as pointers to ordinary variables.They can also be initialized by using the new operator.Example :class C {inti ;public :C(int x) : i(x) { } C() : i(9) {}void f( ) { }} ;main( ) {C *p1 = new C(9) ;Co ;C*p2 = &o ;}

  • C++Horizon*Object pointers can be used to access the members using the arrow operator.

    *ptr can be used with the same meaning. Thus in the previous example :(*p1).f( ) is valid.

  • C++Horizon*this Pointerthis is a pointer to that very object on which the function is invoked.Example :class C {inti ;public :C(int i) { this->i = i ; }void disp( ) { cout
  • C++Horizon*Accessing Derived Class Objects Through Base PointersA base class pointer can be used to point to a derived class object.

    If the base class does not contain any virtual functions then the members referred by using such a pointer are those belonging to the base class.

  • C++Horizon*Class ConversionAn object of a derived class can be used as if it were an object of its base classExample :class Base{..};class Derived : public Base{.};void main(void){Derived d;Base b;b = d;// class conversion}

    An object of the base class cannot be used as an object of a derived class

  • C++Horizon*OverridingA derived class can define a member with the same name as a base class member

    Referring to its name in the derived class, accesses the member in the derived classclass Base {int i;public:Base(int x){ i = x;} // constructor};class Derived :: public Base{ int i;public:Derived(int x){i = x};// Derived :: ivoid CalculateTotal(void){int total = i + Base :: i; }};

  • C++Horizon*

    Create the class relationships for the following fig :QualificationStaffTeacherTypistOfficerRegularCasualSalaryExercises

  • C++Horizon*Create two more classes Student and College. The College class maintains lists of the teachers on a per subject basis. The list-functions are to be used from a LinkedList class. Use the Teacher class from the previous question. The Student class provides with functions selectTeacher(subject, College) which allows him to select a teacher for a specific subject. This function uses the dispTeacherDetails(subject) function of the College class to see the list of name and qualification of the teacher.

  • C++Horizon*Input/Output Operations

  • C++Horizon*Streams I/O LibraryI/O library include file :

    I/O function are still supported by C++

    Problem with I/O of Cprintf , scanf etc cannot be overloaded

    New format specifiers for user defined types cannot be added

    Lack of type checking

    Note : There are many independent implementations of the stream I/O library and the set of facilities described here is only a subset of the actual library.

  • C++Horizon*ostreamistreamiosiostream

  • C++Horizon*cout is a predefined output stream attached to the standard output device

  • C++Horizon*cerr is a predefined error output stream attached to the standard error device.

  • C++Horizon*Stream ExtractionFetches data from an input stream

    The >> (right shift) operator is overloaded as the extraction operator

    cin is associated with the standard input device

    Three types of extractorsintegralfloating pointcharacter

  • C++Horizon*All extractors skip leading white spaces

    Integral extractorsRead input characters until any that cannot be part of the type123x456 is read as 123 with input pointer at x

    Floating point extractorsRead input characters until any that cannot be part of the type123e-4x5 is read as 123.0e-4 with input pointer at x

    Character extractorReads the text character in the input stream skipping leading white spaceschar * or string extractors read all input characters, skipping leading white spaces, upto the next white spaceThis string is read as This

  • C++Horizon*Multiple data items can be read in a single statement by chaining operators together.Example :void main(void) {char c ; int i ; float f;char * buf[30];cin >> c >> i >> f ;}void main(void) {inti ; charc ; doubled ;

    cin>>i>>c>>d ;cout

  • C++Horizon*I/O FormattingSpecial methods are defined for formatting stream objects.The width method specifies I/O widthFor cin , only the specified numbers of characters are readFor cout , the output is displayed right justified in a field of the specified widthIf the length of input is greater than the current width , the entire value is displayed for coutExample :char buf[21];cin.width(20);//only 20 characters read at a timecin >> buf ;int x = 1;cout.width(5);cout
  • C++Horizon*The precision method sets the number of digits after the decimal pointInvolved when a float or double is displayed

    Invoked with or without an int argument

    Example :void main(void) {float pi = 3.14159 ;cout.precision(3);cout

  • C++Horizon*The fill method sets the character used for padding extra space when calling width is default fill character

    Invoked only if the value set using width is greater than the length of the inserted valueExample :void main ( ) { int x = 10 ;cout.fill(0);cout.width(5);cout

  • C++Horizon*Format FlagsStreams recognize flags to control format of input and outputleft , right , internalOnly one of these may be set at any timeIf left is set , inserted data is left justifiedIf internal is set , the sign of a numeric is left justified and the value is right justifiedExtra space in a field of set width is filled with the fill characterIf two of these are unset , the third is automatically setfloat pi = 3.14159 ;cout.precision(3) ;cout.width(8) ;cout.fill(#) ;cout.setf(ios::left) ;cout
  • C++Horizon*dec , oct , hexOnly one of these may be set at any timeThese control the base in which numbers are displayedOn extraction, the integral values are assumed and interpreted to be in the set formatdec is set by default

    showbasePrefaces integral insertions with the base indicators used with C++ constantsIf hex is set , 0x is inserted in front of any integral insertion and if oct is set then 0is insertedThis flag is not set by default

    showposA + sign is inserted before any integral insertionRemains unset by default

  • C++Horizon*uppercaseAll letters in numeric insertions will be converted to upper caseUnset by defaultshowpointForces the display of trailing zeros and decimal points in float and double insertionUnset by default

    scientific , fixedIf scientific is set , floating point values are inserted using scientific notationOne digit before the decimal point , precision digits after it , an e and the exponent value are present for the scientific notationIf fixed is set , the value is inserted using decimal notation , with precision digits following the dicimal pointBy default , scientific notation is used when the exponent is less than -4 or greater than precision

  • C++Horizon*unitbufThe stream is flushed after every insertionThe flag is unset by defaultstdioFlushes the stdout and stderr devices defined in the stdio.hUnset by default

    Flags are stored as bits in a long member of every stream

    Flags are set, unset and read by the following stream methodslong flags( )returns the current format flagslong setf(long f)sets the format flags to freturns the previous flag valuelong unsetf(long f)unsets the flags that are set in freturns the previous flag value

  • C++Horizon*The bit values for the flags are members of an unnamed enumerated type defined in the ios class

    Flags can be ored (|) together to set/unset several flags in one statement

  • C++Horizon*Example :

    #include void main ( ){double pi = 3.1415927 ;int x = 1234 ;// set new flagscout.setf( ios :: hex | ios :: showbase | ios :: uppercase | ios :: scientific) ;cout

  • C++Horizon*ManipulatorsManipulatorsChange the format flags and values of a streamAre set in the stream itselfExample :int x = 1 , y = 2 ;// sets the widthcout
  • C++Horizon*endsInserts a NULL characterUsually used to terminate a string

    flushForces all insertions in the stream to be physically written to the appropriate device

    setfill(char f)Changes the fill character to fThe default fill character is

    setw(int w)change the field width to wIs valid only for text insertionDefault field width is 0

  • C++Horizon*setprecision(int p)Sets the precision for floating point insertions to pThe default precision is 6

    setiosflags(long f)Sets the flags that are set in f

    resetiosflags(long f)Unsets the flags set in f

    Header filesInclude iostream.h and iomanip.h

  • C++Horizon*Other input streams functiontie(ostream)Attaches an output stream to an input streamOutput stream is flushed before extractions on the input streamcin.tie(cout) ; // flushes cout before cincin.tie(0) ; // unties cin from cout

    ignore(int i)Unconditionally ignores the next i characters for cin cin.ignore(5);

    peek( )The next character in the input stream can be looked at without actually fetching i char ch = cin.peek()

  • C++Horizon*putback(char ch)Returns the last character that has been fetched to the input bufferAn error may occur if the stream cannot accept the putback character

    get( )Reads the next character from the input streamchar ch = cin.get( );get() is overloaded with other version

    get(char *str, int len, char delim = \n)Fetches characters from the input stream into the array strfetching is stopped if the len characters have been fetchedFetching is also stopped if delim character is encounteredNext read occurs at the delimiter

  • C++Horizon*get(char &ch)Fetches the next character in the stream and stores it in ch

    getline(char *str, int len, char delim = \n)similar to get(char *, int, char)Extracts the terminator alsoNext read occurs after the delimiter

    put(char ch)A single character is written to an output stream without translation

  • C++Horizon*C++ Stream ClassesDeclared in iostream.h

    Stream classes for console operations are :ios (General input/output stream class)Contains basic facilities that are used by all other input and output classesIt also contains a pointer to a buffer object (streambuf object)Declares constants and functions that are necessary for handling formatted input and output operations

    istream (Input stream)Inherits the property of ios classDeclares input function such as get(),getline() and read()Contains overloaded extraction operator >>

  • C++Horizon*ostream (Output stream)Inherits the property of ios classDeclares output function such as put() and write()Contains overloaded insertion operator
  • C++Horizon*Classes for File OperationC++ I/O system contains set of file stream classes in fstream.h

    Includes filebufIts purpose is to set the file buffers to read and writeAlso contains open() and close() method

    fstreambaseProvides operations common to the file streamsServes as base for fstream,ifstream and ofstreamContains open() and close() method

  • C++Horizon*ifstream classProvides input operations Contains open() with default input modeInherits the functions get(),getline(),read(),seekg() and tellg() from istream

    ofstream classProvides output operations Contains open() with default output modeInherits the functions put(),seekp(),write() and tellp() from ostream

    fstream classProvides support for simultaneous input and output operations Contains open()Inherits the functions from istream and ostream classes through iostream

  • C++Horizon*Opening A FileFor opening a file Create the file stream objectLink the file stream with filename

    Two ways to open file Using constructor function of the classCreate a file stream object to manage the stream using appropriate classInitialize the file object with the desired filenameExample :ofstream outfile(myfile.hcl) ;

    This statement opens the file myfile.hcl and attaches it to output stream outfileThis method is more appropriate when we use only one file in the stream

  • C++Horizon*Using the member function open() of the classCreate a file stream object to manage the stream using appropriate classCall open() method of stream object with the desired filenameExample :ofstream outfile ; // creates streamoutfile.open(myfile.hcl) ; // connects This statement opens the file myfile.hcl and attaches it to output stream outfile

    This method is used when we want to manage multiple files using one stream object.

  • C++Horizon*open() member function can take one OR two arguments

    open(filename , filemode)filename , specifies the file to be opened

    filemode , specifies the purpose for which file is opened

    Prototype for open() contains default values for filemode argumentios::in for ifstream functions meaning open for reading only

    ios::out for ofstream functions meaning open for writing only

  • C++Horizon*File mode constants are defined in the class ios

    Filemode parameter can take one or more filemode constantsios::appAppends to end of fileios::ateGo to end of file on openingios::inOpen file for reading onlyios::nocreateOpen fails if file does not existsios::noreplaceOpen fails if file already existsios::outOpen file for writing onlyios::truncDelete content of file if it exists

  • C++Horizon*File Pointers & ManipulationsEach file has two file pointers associated with itInput pointer (get pointer)Output pointer (put pointer)

    Input pointer is used for reading the content from file

    Output pointer is used for writing to the file

    Pointer advances automatically on each input/output operation

    File stream classes provide functions for file pointer manipulation

  • C++Horizon*Fun