Tuesday, 26 November 2013

C++,virtual function and abstract class

C++ Virtual Functions,Abstract Class,Templates,Overloading,Special Member Function

Introduction

This article describes basic concepts of C++ Virtual functions and abstract class

Virtual Functions

  • By default, C++ matches a function call with the correct function definition at compile time.This is called static binding
  • You can specify that the compiler match a function call with the correct function definition at run time; this is called dynamic binding
  • You declare a function with the keyword virtual if you want the compiler to use dynamic binding for that specific functions
  • The virtual keyword indicates to the compiler that it should choose the appropriate definition of f() not by the type of reference, but by the type of object that the reference refers to.
  • a virtual function is a member function you may redefine for other derived classes, and can ensure that the compiler will call the redefined virtual function for an object of the corresponding derived class, even if you call that function with a pointer or reference to a base class of the object.
  • A class that declares or inherits a virtual function is called a polymorphic class.
  • You redefine a virtual member function, like any member function, in any derived class. Any member function declared as virtual with same name in derived class is also considered as virtual,irrespective of the parameter type
  • A virtual function cannot be global or static because, by definition, a virtual function is a member function of a base class and relies on a specific object to determine which implementation of the function is called. You can declare a virtual function to be a friend of another class.
  • If a function is declared virtual in its base class, you can still access it directly using the scope resolution (::) operator. In this case, the virtual function call mechanism is suppressed and the function implementation defined in the base class is used.
  • In addition, if you do not override a virtual member function in a derived class, a call to that function uses the function implementation defined in the base classes
  • The return type of an overriding virtual function may differ from the return type of the overridden virtual function. The derived class return a pointer or reference to a class which is a direct or indirect base class of type returned by the Base class.
  • You cannot override one virtual function with two or more ambiguous virtual functions. This can happen in a derived class that inherits from two nonvirtual bases that are derived from a virtual base class.
  • As long as ambiguous function is not called,the compiler will not give error
  • The access for a virtual function is specified when it is declared. The access rules for a virtual function are not affected by the access rules for the function that later overrides the virtual functions
  • If a virtual function is called with a pointer or reference to a class object, the type of the class object is not used to determine the access of the virtual function. Instead, the type of the pointer or reference to the class object is used.
  • An abstract class is a class that is designed to be specifically used as a base class. . An abstract class contains at least one pure virtual function
  • You declare a pure virtual function by using a pure specifier (= 0) in the declaration of a virtual member function in the class declaration.
  • You cannot use an abstract class as a parameter type, a function return type, or the type of an explicit conversion, nor can you declare an object of an abstract class. You can, however, declare pointers and references to an abstract classes
  • A function declaration cannot have both a pure specifier and a definition.A pure declaration forces a definition in the derived class.
  • Virtual member functions are inherited. A class derived from an abstract base class will also be abstract unless you override each pure virtual function in the derived class.
  • Note that you can derive an abstract class from a nonabstract class, and you can override a non-pure virtual function with a pure virtual function.
  • You can call member functions from a constructor or destructor of an abstract class.
  • However, the results of calling (directly or indirectly) a pure virtual function from its constructor are undefined.
  • If you declare a base class destructor as virtual, a derived class destructor will override that base class destructor, even though destructors are not inherited.

Monday, 25 November 2013

C++ Inheritance

C++ Inheritance

Introduction

This article describes basic concepts of C++ Inheritance mechanism.

Inheritance

  • Inheritance is a mechanism of reusing and extending existing classes without modifying them, thus producing hierarchical relationships between them.
  • Inheritance is implemented in C++ through the mechanism of derivation. Derivation allows you to derive a class, called a derived class, from another class, called a base classes
  • The class whose members you want to include in your new class is called a base class. Your new class is derived from the base class.
  • You can also add new data members and member functions to the derived class.
  • When you derive a class, the derived class inherits class members of the base class. You can refer to inherited members (base class members) as if they were members of the derived classes
  • You can modify the implementation of existing member functions or data by overriding base class member functions or data in the newly derived class. If a member of a derived class has the same name as a base class, the base class name is hidden in the derived class.
  • You may derive classes from other derived classes, thereby creating another level of inheritance. The number of levels of inheritance is only limited by resources.
  • The new class contains a subobject of the type of the base classes

    Multiple Inheritance

  • Multiple inheritance allows you to create a derived class that inherits properties from more than one base classes
  • Because a derived class inherits members from all its base classes, ambiguities can result
  • In case of ambigious data members a solution would be to override the base class members
  • we can still access the override members of the base class using scope resolution operator
  • A direct base class cannot appear in the base list of a derived class more than once:
  • A derived class can inherit an indirect base class more than once.However this may result in ambiguities since it can be considered that 2 subobjects of Parent class exist which are both accessible throught the derived class.
  • Virtual Base Class

  • A derived can have virtual and non virtual base classes
  • If a derived classes ,inherits from same base class via multiple inheritance,it will have 2 subobjects of the base class leading to ambiguity,hence the virtual base class keyword can be used to specify that derived object contain only one copy of the inherited base class.
  • In an inheritance containing virtual base classes, a name of class member that can be reached through more than one path of inheritance is accessed through the path that gives the most access.

    Ambiguous base classes

  • The order of derivation is relevant only to determine the order of default initialization by constructors and cleanup by destructors.

    Using Keyword Declaration

  • A member function in the derived class will hide all other members with same name in the base class regardless of type of arguments or return type
  • A using declaration in a definition of a class A allows you to introduce a name of a data member or member function from a base class of A into the scope of A
  • If the function with same names as that of base class declared with using keyword is present in the derived class the function in base class will be hidden and no conflict arises.
  • Using Declaration cannot resolve ambiguities due to same inherited members
  • The declaration of a member with an ambiguous name in a derived class is not an error. The ambiguity is only flagged as an error if you use the ambiguous member name.

    Pointer Derived Class and Base Class

  • Pointer to a Derived class can be converted to pointer of the base class
  • A pointer to base class cannot be derived to case class.
  • Members and friends of a class can implicitly convert a pointer to an object of that class to a pointer to either protected or public direct or indirect base class and direct private base class.
  • A direct base class is a base class that appears directly as a base specifier in the declaration of its derived class. An indirect base class is a base class that does not appear directly in the declaration of the derived class but is available to the derived class through one of its base classes For a given class, all base classes that are not direct base classes are indirect base classes. The following example demonstrates direct and indirect base classes
  • Classes that are declared but not defined are not allowed in base lists.

    Inherited member access

  • while inheriting the members from base class,we can hide some information of the base class.This can be done by specifying the access specifier.
  • An access specifier can be public, private, or protected.
  • In a public base class access the public and protected members of the base class remain public and protected members of the derived class respectively.
  • In a protected base class access the public and protected members of the base class are protected members of the derived class.
  • In a private base class access the public and protected members of the base class become the private members of the derived class.
  • The private members of the base class remain private members of derived classes
  • Private members of the base class cannot be used by the derived class unless friend declarations within the base class explicitly grant access to them.
  • The default access specifier is private

    Increasing Access

  • Suppose class B is a direct base class of class A. To restrict access of class B to the members of class A, derive B from A using either the access specifiers protected or private.
  • To increase the access of a member x of class A inherited from class B, use a using declaration.You cannot restrict the access to x with a using declarations
  • Access can be increase to member inherited as private or declared/inherited as protected
  • Access to members declared as private in the base class cannot be increased
  • Access to a member cannot be reduced with a using declaration

Sunday, 24 November 2013

C++ static members and function

C++ Static Members

Introduction

This article describes basic concepts of C++ Storage Access Specifiers.

Storage Access Specifiers

  • A storage class specifier is used to refine the declaration of a variable, a function, and parameters.
  • A storage class specifier do not specify the scope but combined with scope to determine the storage duration and visibility of items.
  • The storage class specifier used within the declaration determines whether:
    • The object is to be stored in memory or in a register, if available
    • The object has internal, external, or no linkage
    • The object can be referenced throughout a program or only within the function, block, or source file where the variable is defined
    • The storage duration for the object is static (storage is maintained throughout program run time) or automatic (storage is maintained only during the execution of the block where the object is defined)
  • - In C / C++ there are 4 different storage classes available: auto,extern,register,static,mutable
  • How these specifiers affect objects depend also on the scope in which they appear.
  • Storage class specifiers are keywords you can use in declarations to control storage duration and linkage.
  • The linkage determines if declaration in different scopes can refer to the same object.
  • - Storage class specifiers tell compiler the duration and visibility of the variables or objects declared, as well as, where the variables or objects should be stored.

    Static Storage Specifier

  • Class members can be declared using the storage class specifier static in the class member list
  • The declaration of a static data member in the member list of a class is not a definition. It must be defined outside the class declaration.
  • When you declare an object of a class having a static member, the static member is not part of the class object.
  • Only one copy of the static member is shared by all objects of a class in a program.
  • You can access a static member of a class by qualifying the class name using the :: (scope resolution) operator
  • Once you define a static data member, it exists even though no objects of the static data member's class exist. The progam will print value 10.
  • Static data members of a class in namespace scope have external linkage The following command shows the symbols with extern linkage and we can find the static data member in this list.The $-g$ indicates only symbols with extern linkages are displayed.We can also see that symbol is initialized in the data section which is indicated by $\mathcal{D}$

  • A static data can be initialized while defining in in namespace scope.
  • A static data member can also be initialized while declaring the class only if it is also declared as const.
  • A static data member cannot be declared as mutable
  • Local Classes cannot have static data members.
  • static data member can be of any type except void or void qualified with const or volatile.
  • Static data members and their initializers can access other static private and protected members of their classes

    Static Member function

  • You cannot have static and nonstatic member functions with the same names and the same number and type of arguments.
  • Like static data members, you may access a static member function of a class without the object of the class
  • A static member function does not have a this pointer
  • A static member function can be declared with const,volatile type qualifiers
  • A static member function cannot be declared as virtual function
  • A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared
  • A static member function cannot access the non static members of the class or base class class X{ public: int b; static int a; enum mode{a1,a2,a3}; static int inc() { return b;//this will give an error } X(){}; };
  • Static data members of class have extern linkage,they can be accessed and duration is the lifetime of the program. This can be used for class members that are required to be used in all the files and its value retained across all the files, for example logging class,monitoring class etc.
  • If a class object is defined as static,then this serves as a static storage access specifier,which defines the scope of the item to be file scope,duration is program execution and linkage is internal linkage.

Saturday, 23 November 2013

C++ Const,Volatile Type Qualifiers

Introduction

This article describes basic concepts of C++ const and volatile type qualifiers.

Type Qualifiers

  • Type specifiers indicate the type of the object or function being declared.
  • Type Qualifiers adds refinement to the type of the object or function being declared.
  • C++ recognizes const and volatile type qualifiers.

    Const Type Qualifiers

  • C const qualifier explicitly declares a data object as something that cannot be changed
  • A const object or variable must be initialized and its value is set at initialization.
  • In case of class object,all the member variables must be initialized in the constructor A default user defined constructor will initialize all the values to random value.
  • When object is defined as constant,no data members of class can be modified,or any non-constant member function cannot be called.
  • You cannot use const data objects in expressions requiring a modifiable lvalue,ie left side of assignment
  • An object that is declared const is guaranteed to remain constant for its lifetime, not throughout the entire execution of the program. And thus const variables cannot be used in place of constant or in a constant expression. The const variable k is const for the lifetime of the function,it is initialized to value of j at the start of the function and remains a const till the function returns only.
  • A const variable has internal linkage by default,storage qualifiers need to be specified explicitly. Const Objects can be used in header files,since they have internal linkages and can be used instead of \#define for constant values;
  • For a const pointer, you must put the keyword between the * and the identifier In this case the the value of pointer/address cannot be changed but the value the pointer is pointing to can be changed.
  • To define a pointer to a const value,the keyword must be placed before the type specifier. We can change the values of a,b,c and since in the last line pointer points to address of b,we can deference the pointer and obtain the value of new variable.
  • we can see that the pointer can be changed,however changing the value the pointer y points gives a error.It is a pointer to a const integer

    Any expression of the form $*y=1$ will give an error.We cannot change the value of the variable via pointer. \\
  • In the below expression neither the value pointed to or the pointer can be changed
  • Declaring a member function as const means that the this pointer is a pointer to a const object. \\ There are reasons that you will want the compiler to prevent a member function from being able to change any private member variables of the calling objects \\
  • The data member of class will be constant within that function.
  • A const member function cannot call any non-const member function
  • If a object of class is delared as const,it can only call const functions of the class,but not non-const functions of the class.Delaring the object as const means that this pointer is a pointer to a const object.
  • If a function is defined as const we can still change the value using const_cast A better approach would be to declare the variable desired to be changed as mutable.
  • The mutable storage class specifier is used only on a class data member to make it modifiable even though the member is part of an object declared as const or function is declared as const.
  • - Pointer to constant data can be used as function parameters to prevent the function from modifying a parameter passed through a pointer or passed as a reference.
  • The member function can also return a const value or reference to const value. A return of a object invokes a copy constructor while returning a reference does not invoke a copy constructor.Thus for efficiency it can be used.However the return by reference supplies the local address of a variable,not if the main object has been deallocated,the value which address points to is undefined. \\ The reference should be to an object that exists. we can see that value pointed by x4 is difference after the object has been deallocated. This is inherent drawback of call be reference,where user must ensure that the object is not being referenced.
  • however in case of applications like streaming camera frames,sensor data etc we do not want to allocate a new address for every new frame of data . In this case returning a constant reference or pointer provides a effcient way of providing the data without copying it or allocating it everytime.

    Volatile Type Qualifier

  • The volatile qualifier maintains consistency of memory access to data objects
  • Volatile objects are read from memory each time their value is needed, and written back to memory each time they are changed.
  • The volatile qualifier declares a data object that can have its value changed in ways outside the control or detection of the compiler and the compiler is thereby notified not to apply certain optimizations to code referring to the object.
  • When applied to a class ,all members of the class have the same type qualifiers.
  • An item can be both volatile and const.In which case the item is modified by some asynchronous process.
  • You can define or declare any function to return a pointer to a volatile or const function.
  • You can declare or define a volatile or const function only if it is a nonstatic member function.

Friday, 22 November 2013

C++ Class Members and Friends

C++ Class Members and friends

Introduction

This article tells us how to grant access to its non public members by the use of friend mechanism.

Friend Mechanism

  • A friend of a class X is a function or class that is not a member of X, but is granted the same access to X as the members of X
  • Functions declared with the friend specifier in a class member list are called friend functions of that class
  • Classes declared with the friend specifier in the member list of another class are called friend classes of that class.
  • A class Y must be defined before any member of Y can be declared a friend of another class.
  • We can define a function as a friend or an entire class as friend. The function can be a member of a class or declared in the global namespace. The function needs to be declared before it can be used as friend.
  • If a friend function is a member of another class,a scope resolution operator needs to be used ,for example Y::print(X\& x);
  • however a function can be defined provided function is unqualified and has namespace scope (function is not a member of function of another class or declared in another workspace) and class is non local.
  • If a class F is a friend of class A,then every member function and static data member definition of class F has access to class A.
  • For using the class as a friend,in the declaration must be elaborated class name , for example friend class F
  • A friend class can be defined after it is declared as friend in other class
  • A friend cannot be declared with a storage class specifier.
  • A class cannot be defined within a friend declaration,
  • The scope of a friend class name is the first nonclass enclosing scope In the example the scope of the friend class name is class Z1 and not class
  • Friends of a base class are inherited by any classes derived from that base class The functionality that the friend of the base class are inherited by the derived by the base class may be compiler dependent.The g++ compiler on Linux supports this feature,while many online references suggest this inheritance does not hold.
  • If a class is derived from a friend class ,then it is also a friend of the original base class.This feature may also be compiler dependent.The g++ compiler on Linux supports this feature,while many online references suggest this inheritance does not hold.
  • Friendships are not transitive if A is a friend of B,and C is a friend of A,it does not imply that C is a friend of B unless explicitly specified.

code

The code used in the article can be found in Git repository https://github.com/pi19404/m19404/tree/master/CPP/t1