C++ PROGRAMMING BASICS:
 
The major purpose of C++ programming is to introduce the concept of object orientation to the C programming language.


FEATURES OF OOP:
Object.
Class.
Data Hiding and Encapsulation.
Dynamic Binding.
Message Passing.
Inheritance.
Polymorphisam


C++ Programming basics:


Output and Input using cout and cin:

C++ Input/Output. ... There are two variables (among others) defined in <iostream>. cout is used for output, cin for input. Important Point. cout and cin are not key words in the C++ language. They are variables, instances of classes, that have been declared in <iostream>. cout is a variable of type ostream.
Preprocessor programs provides preprocessors directives which tell the compiler to preprocess the source code before compiling. All of these preprocessor directive begins with a '#' (hash) symbol. This ('#') symbol at the beginning of a statement in a C/C++ program indicates that it is a pre-processor directive.
Type Bool:
Definition: Bool is a fundamental type in C, C++ and C# languages. Variables of this type can only take two values- 1 and 0. In C++ these correspond to true and false and can be used interchangably.
Boolean Data Type --- bool. In C++, data type bool is used to represent Boolean data. Each bool constant or variable contains one of two values: true or false. true and false are two C++ constants.
The setw Manipulator:
The C++ function std::setfill behaves as if member fill were called with c as argument on the stream on which it is inserted as a manipulator (it can be inserted on output streams). It is used to sets c as the stream's fill character.Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects, for example: cout << boolalpha; …
Type Conversions:
In computer science, type conversion or typecasting refers to changing an entity of one datatype into another. There are two types of conversion: implicit and explicit.
Implicit Type Conversion Also known as 'automatic type conversion'. Done by the compiler on its own, without any external trigger from the user. ...
Explicit Type Conversion: This process is also called type casting and it is user-defined.

Functions:

      Returning values of functions:
A function is a group of statements that together perform a task. Every C++ program has at least one function, which is main(), and all the most trivial programs can define additional functions.
A function declaration tells the compiler about a function's name, return type, and parameters. A function definition provides the actual body of the function.

The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.
The general form of a C++ function definition is as follows −
return_type function_name( parameter list ) {
  body of the function
}
A C++ function definition consists of a function header and a function body. Here are all the parts of a function −

Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

       Reference arguments:
To pass the value by reference, argument reference is passed to the functions just like any other value. So accordingly you need to declare the function parameters as reference types as in the following function swap(), which exchanges the values of the two integer variables pointed to by its arguments.
References allow a function to change the value of the argument, which is sometimes useful. Otherwise, const references can be used to guarantee the function won't change the argument. Because a copy of the argument is not made, pass by reference is fast, even when used with large structs or classes.
       Overloaded functions:
Function overloading (also method overloading) is a programming concept that allows programmers to define two or more functions with the same name and in the same scope. Each function has a unique signature (or header), which is derived from: function/procedure name. number of arguments. arguments' type.
        Inline functions:
The inline functions are a C++ enhancement feature to increase the execution time of a program. Functions can be instructed to compiler to make them inline so that compiler can replace those function definition wherever those are being called.
Inline function instruct compiler to insert complete body of the function wherever that function got used in code. It also save overhead of variables push/pop on the stack, while function calling. It also save overhead of return call from a function.
Benefits of inline functions
Inline functions provide following advantages: 1) Function call overhead doesn't occur. 2) It also saves the overhead of push/pop variables on the stack when function is called.
          Default arguments:
A default argument is a value provided in function declaration that is automatically assigned by the compiler if caller of the function doesn't provide a value for the argument with default value. Following is a simple C++ example to demonstrate use of default arguments.
In C++ programming, you can provide default values for function parameters. The idea behind default argument is simple. If a function is called by passing argument/s, those arguments are used by the function. But if the argument/s are not passed while invoking a function then, the default values are used.
           Returning by reference:
A C++ function can return a reference in a similar way as it returns a pointer. When returning a reference, be careful that the object being referred to does not go out of scope. So it is not legal to return a reference to local var. But you can always return a reference on a static variable.

Object and classes:

            Classes:
The building block of C++ that leads to Object Oriented programming is a Class. It is a user defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brand but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.
      Objects:
An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated.
       Datahiding:
Data hiding and encapsulation both are the important concept of object oriented programming. Encapsulation means wrapping the implementation of data member and methods inside a class. ... Data Hiding means protecting the members of a class from an illegal or unauthorized access.
       Dynamic binding:
C++ provides facility to specify that the compiler should match function calls with the correct definition at the run time; this is called dynamic binding or late binding or run-time binding. Dynamic binding is achieved using virtual functions. Base class pointer points to derived class object.
        Message passing:
Message passing is a type of communication between processes. Message passing is a form of communication used in parallel programming and object-oriented programming. Communications are completed by the sending of messages (functions, signals and data packets) to recipients. See also Message Passing Interface (MPI).
        Inheritance:
Inheritance is the capability of one class to acquire properties and characteristics from another class. The class whose properties are inherited by other class is called the Parent or Base or Super class. And, the class which inherits properties of other class is called Child or Derived or Sub class.
Inheritance makes the code reusable. When we inherit an existing class, all its methods and fields become available in the new class, hence code is reused.Inheritance provides the idea of reusability of code and each sub class defines only those features that are unique to it. Object-Oriented Programming has the following advantages: ... OOP makes it easy to maintain and modify existing code as new objects can be created with small differences to existing ones.
         Polymorphism:     
The word polymorphism means having many forms. Typically, polymorphism occurs when there is a hierarchy of classes and they are related by inheritance. C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.The word 'polymorphism' literally means 'a state of having many shapes' or 'the capacity to take on different forms'. ... Method overloading is an example of static polymorphism, while method overriding is an example of dynamic polymorphism.
C++ supports three kinds of polymorphism: ad-hoc polymorphism (through function overloading, and implicit conversions), parametric polymorphism (through template specializations and tag dispatching), and subtype polymorphism (through the virtual function call mechanism).
          Association:
An association supports data sharing between classes or, in the case of a self-association, between objects of the same class. For example, a Customer class has a single association (1) to an Account class, indicating that each Account instance is owned by one Customer instance.
          Interfaces:
Interfaces in C++ (Abstract Classes) An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class. ... Failure to override a pure virtual function in a derived class, then attempting to instantiate objects of that class, is a compilation error.
           Implementation of class in C++:
The structure of a class implementation file. An implementation file is used in C++ programming when creating a class definition to split the interface from the implementation. The header file would declare all the member functions (methods) and data methods (fields) that the class has.
           C++ Constructors:
A constructor is a special type of member function that initialises an object automatically when it is created. Compiler identifies a given member function is a constructor by its name and the return type. Constructor has the same name as that of the class and it does not have any return type.
             C++ Objects As Function Arguments:
Similar to variables, object can be passed to functions. The following are the three methods to pass argument to a function: Pass-by-value – A copy of object (actual object) is sent to function and assigned to the object of callee function (formal object).
             C++ Copy Constructor:
Initialize one object from another of the same type. Copy an object to pass it as an argument to a function.
             C++ - Returning object from function:
A function can also return objects either by value or by reference. When an object is returned by value from a function, a temporary object is created within the function, which holds the return value.
A data structure is a group of data elements grouped together under one name. These data elements, known as members, can have different types and different lengths.
The main difference that exists between them is regarding the access modifier; the members of a class are private by default, whereas members of a struct are public by default. A class in C++ is just an extension of a structure used in the C language. It is a user defined data type.
Static members (C++ only) Class members can be declared using the storage class specifier static in the class member list. Only one copy of the static member is shared by all objects of a class in a program. ... A typical use of static members is for recording data common to all objects of a class.
In statement (a), the const modifier enables to assign an initial value to a variable that cannot be changed later by the program. For example, const age = 40; ... When the const variable is used with a pointer argument in a function's parameter list, the function cannot modify the variable that the pointer points to.

Arrays and string arrays fundamentals.Arrays as class member data:

         Arrays of Objects:
An array of objects, all of whose elements are of the same class, can be declared just as an array of any built-in type. Each element of the array is an object of that class. Being able to declare arrays of objects in this way underscores the fact that a class is similar to a type.
C++ provides following two types of string representations −

The C-style character string.
The string class type introduced with Standard C++.
The C-Style Character String
The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
The String Class in C++
The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality.
string class is part of C++ library that supports a lot much functionality over C style strings. C++ string class internally uses char array to store character but all memory management, allocation and null termination is handled by string class itself that is why it is easy to use.
Example:
C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).


Operator overloading:

          Overloading unary operations:
C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).Overloading unary operators (C++ only) You overload a unary operator with either a nonstatic member function that has no parameters, or a nonmember function that has one parameter. Suppose a unary operator @ is called with the statement @t , where t is an object of type T .
           Overloading binary operators:
A binary operator is an operator that operates on two operands and manipulates them to return a result. Operators are represented by special characters or by keywords and provide an easy way to compare numerical values or character strings.Overloading with a single parameter is called binary operator overloading. ... Binary operators require two operands, and they are overloaded by using member functions and friend functions. Overloading binary operators using member functions. If overloaded as a member function, binary operators require one argument.
           Data Type Conversion in C++:
The process of converting the data type of a value in another data type is known as data type conversion. ...
It convert data type to another data type automatically. ...
In this case, the result of an expression is evaluated to larger data type in the expression .

There are no pitfalls that are specific to operator overloading, but it does exacerbate another problem which is absurdly prevalent – programmers having no clue what the code semantics are. You don't have to go any further than << and >> operators from the ancient times of iostream.


Inheritance:

           Derived class:
A derived class is a class created or derived from another existing class. The existing class from which the derived class is created through the process of inheritance is known as a base class or superclass.
Class-based programming, or more commonly class-orientation, is a style of Object-oriented programming (OOP) in which inheritance occurs via defining classes of objects, instead of inheritance occurring via the objects alone (compare prototype-based programming).
The most popular and developed model of OOP is a class-based model, instead of an object-based model.
          Constructors in Derived Class:
When a class is declared, a constructor is also declared inside the class in order to initialize data members. ... When a class is derived from another class, it is possible to define a constructor in the derived class, and the data members of both base and derive classes can be initialized.The following example shows the order in which base class and member constructors are called in the constructor for a derived class. First, the base constructor is called, then the base-class members are initialized in the order in which they appear in the class declaration, and then the derived constructor is called.
          Member functions:
The functions declared inside the class are known as member functions. O Member functions are methods or functions that are defined inside of objects. O Generally used to manipulate data members and other object data.
         The Stream Class Hierarchy:
A C++ class is a collection of data and the methods necessary to control and maintain that data. ... A C++ object is a specific variable having a class as its data type. cin and cout are special pre-specified objects with different classes as their data types.
         Public and private inheritance:
A class in C++ is a user defined type or data structure declared with keyword class that has data and functions (also called methods) as its members whose access is governed by the three access specifiers private, protected or public (by default access to members of a class is private).
         C++ Aggregation:
aggregation is a process in which one class defines another class as any entity reference. It is another way to reuse the class. It is a form of association that represents H AS-A relationship
         Nested classes:
Member functions of a nested class follow regular access rules and have no special access privileges to members of their enclosing classes. ...
You can define member functions and static data members of a nested class in namespace scope.
You cannot use a typedef name in an elaborated type specifier.



Pointer:

          Adresses and pointer:
C++ allows you to have pointer on a pointer and so on. Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.
           
C++ allows you to have pointer on a pointer and so on. Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function. C++ allows a function to return a pointer to local variable, static variable and dynamically allocated memory as well.

The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner. printf("The address of ptr is %p\n", (void *) &ptr); to print the address of ptr .

C uses malloc() and calloc() function to allocate memory dynamically at run time and uses free() function to free dynamically allocated memory. C++ supports these functions and also has two operators new and delete that perform the task of allocating and freeing the memory in a better and easier way.

In the C++ programming language, new and delete are a pair of language constructs that perform dynamic memory allocation, object construction and object destruction.[1]

Overview    Edit
Except for a form called the "placement new", the new operator denotes a request for memory allocation on a process's heap. If sufficient memory is available, new initialises the memory, calling object constructors if necessary, and returns the address to the newly allocated and initialised memory.[

The deallocation counterpart of new is delete, which first calls the destructor (if any) on its argument and then returns the memory allocated by new back to the free store. Every call to new must be matched by a call to delete; failure to do so causes memory leaks.[1]
A pointer to a C++ class is done exactly the same way as a pointer to a structure and to access members of a pointer to a class you use the member access operator -> operator, just as you do with pointers to structures. Also as with all pointers, you must initialize the pointer before using it.
C++ Tutorial - Debugging Crash & Memory Leak
Undefined behavior can happen because there are lots of things not specified by the C/C++ standard for a variety of reasons.
Invoking a method with an illegal object pointer is the same as passing an illegal pointer to a function. ...
Segmentation fault occur when a program attempts to access memory not allowed.





Debugging Crash & Memory Leak
Undefined behavior can happen because there are lots of things not specified by the C/C++ standard for a variety of reasons.
Invoking a method with an illegal object pointer is the same as passing an illegal pointer to a function. ...
Segmentation fault occur when a program attempts to access memory not allowed.You use virtual functions when you want to override a certain behavior (read method) for your derived class rather than the one implemented for the base class and you want to do so at run-time through a pointer to the base class.
          Friend function in C++ Programming.
In C++, private members remain hidden and can only be accessed by other member function of that class and friend function. Friend function is defined or declared using keyword 'friend' before the function prototype inside the class.
A C++ friend functions are special functions which can access the private members of a class. They are considered to be a loophole in the Object Oriented Programming concepts, but logical use of them can make them useful in certain cases.
          Static Function Members.
By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator
Copy constructor vs assignment operator in C++ Copy constructor is called when a new object is created from an existing object, as a copy of the existing object (see this G-Fact). And assignment operator is called when an already initialized object is assigned a new value from another existing object.
           C++ this Pointer.
Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object.
            Dynamic type info
RTTI is short for Run-time Type Identification. RTTI is to provide a standard way for a program to determine the type of object during runtime. ... The dynamic_cast operator, which safely converts from a pointer (or reference) to a base type to a pointer (or reference) to a derived type.





A stream is nothing but a flow of data. In the object-oriented programming, the streams are controlled using the classes.The operations with the files mainly consist of two types. They are read and write. C++ provides various classes, to perform these operations. The ios class is the base class.For the most part, these operate in exactly the same way as the standard I/O streams, cin and cout. The types ifstream and ofstream are C++ stream classes designed to be connected to input or output files.
std::cerr is an object of class ostream that represents the standard error stream oriented to narrow characters (of type char). It corresponds to the C stream stderr. The standard error stream is a destination of characters determined by the environment. This destination may be shared by more than one standard object (such as cout or clog).
Input/output with files
C++ provides the following classes to perform output and input of characters to/from files:

ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therefore, we have already been using classes that are related to our file streams.
File Position Pointers. Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream. The argument to seekg and seekp normally is a long integer.
Sometimes during file operations, errors may also creep in. For example, a file being opened for reading might not exist. Or a file name used for a new file may already exist. Or an attempt could be made to read past the end-of-file. Or such as invalid operation may be performed. There might not be enough space in the disk for storing data.

To check for such errors and to ensure smooth processing, C++ file streams inherit 'stream-state' members from the ios class that store the information on the status of a file that is being currently used.
We know that insertion (<<) and extraction (>>) are operators in C++ and just like other operators we can also overload this insertion and extraction operators. In this post I will show you how to overload insertion and extraction operators just like other operators.
Consider the example of class ‘Box’ in which we want to read and print the data members of class by overloading insertion and extraction operator.
// Program to overload insertion and extraction operator

#include "iostream.h"
#include "conio.h"

class Box
{
   double height;
   double width;
   double vol ;
   
   public :
    friend istream & operator >> (istream &, Box &);
    friend ostream & operator << (ostream &, Box &);
};

istream & operator >> (istream &din, Box &b)
{
    clrscr();
    cout << "Enter Box Height: " ; din >> b.height ;
    cout << "Enter Box Width : " ; din >> b.width ;
    return (din) ;
}
ostream & operator << (ostream &dout, Box &b)
{
    dout << endl << endl;
    dout << "Box Height : " << b.height << endl ;
    dout << "Box Width  : " << b.width << endl ;
   
       b.vol = b.height * b.width ;
   
       dout << "The Volume of Box : " << b.vol << endl;
       getch() ;
      
       return(dout) ;
}

void main()
{
      Box b1;

      cin >> b1;
      cout << b1;
}
In above example we are overloading insertion and extraction operator using friend function.
For insertion operator overloading we are passing two arguments.
One is object (‘dout’) of class ‘ostream’ and another is object (‘b’) of class “Box”. Also that function returns the object of type ‘ostream’ as ‘dout’.
You can use any name you like instead of dout.
The C++ stream that extracts information from the input stream is called cin (Console INput). This object uses the multiply-overloaded right-bit-shift operator ( >> ) to feed information from the input stream into variables.
The command line arguments are handled using main() function arguments where argc refers to the number of arguments passed, and argv[] is a pointer array which points to each argument passed to the program.




Function templates.
Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.

    

0 Comments