Articles by "Home"
Showing posts with label Home. Show all posts
no image
Pointers in C++: 

A pointer is a derived data type that refers to another data variable by storing the variables memory address rather than data.
Declaration of the pointer variable is in the following form : 
Eg int * ptr; 
Here ptr is a pointer variable and points to an integer data type. 
We can initialize pointer variable as follows 
int a, *ptr; // declaration ptr = &a //initialization 

Pointers to objects: 
Consider the following eg item X; // where item is class and X is object 
Similarly, we can define a pointer it_ptr of type item as follows 
Item *it_ptr ; 
Object pointers are useful in creating objects at runtime. 
We can also access public members of the class using pointers. 
Eg item X; item *ptr = &X;
the pointer 'ptr' is initialized with address of X. 
we can access the member functions and data using pointers as follows 
ptr->getdata(); 
ptr->show(); 

this pointer: 
C++ uses a unique keyword called this to represent an object that invokes a member function. this is a pointer that points to the object for which this function was called. This unique pointer is automatically passed to a member function when it is called.

Important notes on this pointer:

1. this pointer stores the address of the class instance, to enable pointer access of the members to the member functions of the class.
2. this pointer is not counted for calculating the size of the object.
3. this pointer is not accessible for static member functions.
4. this pointer is not modifiable.


Thanks
Mukesh Rajput
no image
Use of  new and delete operators in C++: 

There is following generic syntax to use the new operator to allocate memory dynamically for any data-type. 
new data-ty 
Here, data-type could be any built-in data type including an array or any user-defined data types include class or structure. Let us start with built-in data types. For example, we can define a pointer to type double and then request that the memory is allocated at execution time. We can do this using the new operator with the following statements: 

double* pvalue = NULL; // Pointer initialized with null 
pvalue = new double; // Request memory for the variable 

The memory may not have been allocated successfully, if the free store had been used up. So it is good practice to check if new operator is returning NULL pointer and take appropriate action as below: 

double* pvalue = NULL; 
if( !(pvalue = new double )) 
{ 
cout << "Error: out of memory." <<endl; 
exit(1); 
} 
The malloc() function from C, still exists in C++, but it is recommended to avoid using malloc() function. The main advantage of new over malloc() is that new doesn't just allocate memory, it constructs objects which is prime purpose of C++. At any point, when you feel a variable that has been dynamically allocated is not anymore required, you can free up the memory that it occupies in the free store with the delete operator as follows: 

delete pvalue; // Release memory pointed to by pvalue
Let us put above concepts and form the following example to show how new and delete work: 
#include <iostream> 
using namespace std; 
int main () 
{ 
double* pvalue = NULL; // Pointer initialized with null 
pvalue = new double; // Request memory for the variable 
*pvalue = 294.89; // Store value at allocated address 
cout << "Value of pvalue : " << *pvalue << endl; 
delete pvalue; // free up the memory. 
return 0; 
} 
If we compile and run above code, this would produce the following result: 
Value of pvalue : 294


Thanks
Mukesh Rajput
no image
Object Oriented Programming  Concepts:

The object oriented paradigm is built on the foundation laid by the structured programming concepts. The fundamental change in OOP is that a program is designed around the data being operated upon rather upon the operations themselves. Data and its functions are encapsulated into a single entity.OOP facilitates creating reusable code that can eventually save a lot of work. A feature called polymorphism permits to create multiple definitions for operators and functions. Another feature called inheritance permits to derive new classes from old ones. OOP introduces many new ideas and involves a different approach to programming than the procedural programming.
Benefits of Object-Oriented Programming: Data security is enforced. Inheritance saves time. User defined data types can be easily constructed. Inheritance emphasizes inventions of new data types. Large complexity in the software development can be easily managed.

Basic C++ Knowledge:
C++ began its life in Bell Labs, where Bjarne Stroustrup developed the language in the early 1980s. C++ is a powerful and flexible programming language. Thus, with minor exceptions, C++ is a superset of the C Programming language.
The principal enhancement being the object –oriented concept of a class. A Class is a user defined type that encapsulates many important mechanisms. Classes enable programmers to break an application up into small, manageable pieces, or objects.

Basic concepts of Object-Oriented Programming:

1) Object: Objects are the basic run time entities in an object-oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle.
2) Class: The entire set of data and code of an object can be made of a user defined data type with the help of a class in fact Objects are variables of the type class. Once a class has been defined, we can create any number of objects belonging to that class. A class is thus a collection of objects of similar type.
For example: mango, apple, and orange are members of the class fruit.
Ex: fruit mango; // will create an object mango belonging to the class fruit.
3) Data Abstraction and Encapsulation: The wrapping up of data and functions in to a single unit is known as encapsulation. Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and only those functions which are wrapped in the class can access. This insulation of the data from direct access by the program is called data hiding. Abstraction refers to the act of representing essential features without including the background details or explanations. Since the classes use the concept of data abstraction, they are known as Abstraction Data Type (ADT).
4) Inheritance: Inheritance is the process by which objects of one class acquire the properties of objects of another class.
For example: The bird 'robin ' is a part of the class 'flying bird' which is again a part of the class 'bird'. The concept of inheritance provides the idea of reusability.
5) Polymorphism: Polymorphism is another important OOP concept. Polymorphism means the ability to take more than one form. An operation may exhibit different instances. The process of making an operator to exhibit different behaviors in different instance is known as operator overloading.
6) Dynamic Binding: Binding refers to the linking of a function to the code to be executed in response to the call. Dynamic Binding (also known as late binding) means that the code associated with a given function which is to be used is not known until the time of the call at run-time. A function call associated with a polymorphic reference depends on the dynamic type of that reference.
7) Message Passing: An object-oriented program consists of a set of objects that communicate with each other. This involves the following basic steps:
1. Creating classes that define objects and their behavior.
2. Creating objects from class definitions, and
3. Establishing communication among objects.
Objects have a life cycle. They can be created and destroyed. Communication with an object is feasible as long as it is alive.


Thanks
Mukesh Rajput
no image
C++ is a programming language 

C++ is a programming language with grammar rules and legal vocabulary, much like any other foreign language. To use it:
a. You create a source code file – a plain text file – containing a “program” written according to the C++ language rules (grammar and vocabulary). Source code is usually saved in a file with a .cpp extension.
b. A special program called a compiler checks the source code file for grammar and vocabulary errors. If there are no errors, the compiler creates the “object file”, a file that contains the original instructions in a machine language format. The object file is not “human readable”. The object file is usually named “somename.obj”.
c. A second program called the linker combines your object file with possibly other object files to form an “executable” file. The executable file contains instructions in a format that the operating system can understand and execute, i.e. this is a real program you can run.
Note that a compiler is not very smart when translating your source code. Every rule of the C++ language must be followed exactly, the compiler does not “know what you mean” unless you specifically and grammatically correctly write down exactly what you mean.

General Formatting:
a. C++ is does distinguish between uppercase and lowercase letters (i.e., it’s case sensitive).
b. Statements must end in a semi-colon.
c. Curly braces { and } are used to group a set of expressions together
d. Comments should be added to your code to clarify it (using either // for short comments or /* … */ for longer comments).

Libraries
C++ provides several libraries of pre-written functions for you that perform frequently needed operations.  You access these libraries by placing #include statements at the top of your source code file.  The most commonly used libraries are listed below.
a. iostream : provides cin and cout
b. cmath : provides math functions like sin(), sqrt() and log10()
c. cstdlib : provides miscellaneous routines like rand()
d. ctime : provides function for manipulating time
e. string : allows use of the string type
f. vector : allows use of the vector type
g. list : allows use of the list type

Variable Declaration
To declare a variable, you must give it a name and a type. 
Syntax:
type varName =  [initialValue]; 
Variable (and function) names should consist of letters, numbers, and the underscore character. They must start with a letter. Spaces are illegal. Note: variable names should always be meaningful. All declared variable have a value. C++ allocates memory and “labels” it when it encounters a declaration.  You may optionally give a variable an initial value when it is declared. 
Example variable declarations:
double pi = 3.14159;
int seconds;
string myName = “Norbert Weiner”;
All variables must be declared before they can be used. Note: Declare variables close to where they are needed and initialize them immediately.

Scope and Scope Rules
The scope of a variable refers to that part of the program where the variable is accessible. There are two scope rules governing the scope of variables (and symbols):
a. The scope of a variable is the codeblock in which it is defined, i.e. a variable is only valid within the block in which it is defined.
b. If two variables by the same name are defined in a block, then the closest declaration counts and hides the original variable.
Global variables are variables whose scope is the entire program. That means that they must be defined outside any function, typically at the top of the program. Every function can access and change a global variable.  Avoid using global variables without good reason.

Constants
Constants are variables whose value cannot change. They are declared the same as variables except that they must be prefaced by the keyword const and must be given a value when they are declared. Syntax;
const type varName = initialValue;
The initial value cannot change throughout the program. As a rule of thumb, never use unnamed constants (plain values) if there is a meaning attached to them. Instead, define a global constant whose name reflects the meaning and use that name instead of the value.


Thanks
Mukesh Rajput
no image
Short Answer type Questions of C/C++ Language

1. What is the need for Destructors? 
Destructor is used to destroy an object. By destroying the object memory occupied by the object is released.

2. Explain the functions of Default Constructor.
The main function of the constructor is, if the programmer fails to create a constructor for a class, then the compiler will create a constructor by default in the name of class name without having any arguments at the time of compilation and provides the initial values to its data members. Since it is created by the compiler by default, the no argument constructor is called as default constructor.

3. What is the need for Overloading an operator. 
To define a new relation task to an operator, we must specify what it means in relation to the class to which the operator is applied. This is done with the help of a special function called operator function. It allows the developer to program using notation closer to the target domain and allow user types to look like types built into the language.

4. What are templates? 
Template is one of the features added to C++. It is new concepts which enable us to define generic classes and functions and thus provides support for generic programming. A template can be used to create a family of classes or functions.

5. Illustrate the exception handling mechanism. 
C++ exception handling mechanism is basically upon three keywords, namely, try, throw, and catch.
try – is used to preface a block of statements which may generate exceptions.
throw - When an exception is detected, it is thrown using a throw statement in the try block.
Catch- A catch block defined by the keyword catch ‘catches’ the exception ‘thrown’ by the thrown statement in the try block and handles its appropriately.

6. What happens when a raised exception is not caught by catch block? 
If the type of object thrown matches the arg type in the catch statement, then catch block is executed for handling the exception. If they do not match the program is aborted with the help of abort() function which is invoked by default. When no exception is detected and thrown, the control goes to the statement immediately after the catch block. That is the catch block is skipped.

7. What is a template? What are their advantages.
A template can be used to create a family of classes or functions. A template is defined with a parameter that would be replaced by a specified data type at the time of actual use of the class or functions. Supporting different data types in a single framework. The template are sometimes called parameterized classes or functions.

8. What is a virtual base class?
When a class is declared as virtual c++ takes care to see that only copy of that class is inherited, regardless of how many inheritance paths exist between the virtual base class and a derived class.

9. What is the difference between base class and derived class?
The biggest difference between the base class and the derived class is that the derived class contains the data members of both the base and its own data members. The other difference is based on the visibility modes of the data members.

10. What are the rules governing the declaration of a class of multiple inheritance?
a. More than one class name should be specified after the : symbol.
b. Visibility modes must be taken care of.
If several inheritance paths are employed for a single derived class the base class must be appropriately declared

11. Define dynamic binding. 
Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time.

12. What do you mean by pure virtual functions?
A pure virtual function is a function declared in a base class that has no definition relative to the base class. In such cases, the compiler requires each derived class to either define the function or re-declare it as a pure virtual function. A class containing pure virtual functions cannot be used to declare any objects of its own.


Thanks
Mukesh Rajput
no image
Short Answer type Questions of C/C++ Language

1. What are objects? How are they created?
Objects are basic run-time entities in an object-oriented programming system. The class variables are known as objects. Objects are created by using the syntax: 
a. Object declaration after the class declaration:
class_name object;
b. Object declaration during the class declaration:

class class_name
{
data member_1;
data member_n;
member function_1;
member function_n;
}
object;

2. Describe the importance of destructor.
A destructor destroys the objects that have been created by a constructor upon exit from the program or block to release memory space for future use. It is a member function whose name is the same as the class name but is preceded by a tilde.
Syntax:
~class_name()
{ 
}

3. What do you mean by friend functions?
C++ allows some common functions to be made friendly with any number of classes, thereby allowing the function to have access to the private data of thse classes. Such a function need not be a member of any of these classes. Such common functions are called friend functions.

4. What are member functions?
Functions that are declared within the class definition are referred as member function.

5. Define dynamic binding.
Dynamic binding means that the code associated with a given procedure call is not known until the time of the call at run-time.

6. Write any properties of constructor.
a. Constructors should be declared in the public section.
b. They are invoked automatically when the objects are created.
c. They do not have return types
d. They cannot be inherited

7. List any Operators that cannot be overloaded.
a. Class member access operator (. , .*)
b. Scope resolution operator (::)
c. Size operator ( sizeof )
d. Conditional operator (?:)

8. What is a Destructor? 
A destructor is used to destroy the objects that have been created by a constructor. It is a special member function whose name is same as the class and is preceded by a tilde ‘~’symbol. When an object goes out from object creation, automatically destructor will be executed.

9. What is the Need for initialization of object using Constructor? 

If we fails to create a constructor for a class, then the compiler will create a constructor by default in the name of class name without having any arguments at the time of compilation and provides the initial values to its data members. So we have to initialize the objects using constructor.

10. What is a Copy Constructor.
A copy constructor is used to declare and initialize an object from another object. It takes a reference to an object of the same class as an argument.


Thanks
Mukesh Rajput
no image
Short Answer type Questions on C/C++ Language

1. What are abstract classes?
Classes containing at least one pure virtual function become abstract classes. Classes inheriting abstract classes must redefine the pure virtual functions; otherwise the derived classes also will become abstract. Abstract classes cannot be instantiated.

2. Define abstraction and Encapsulation.
Abstraction refers to the act of representing the essential features without including the background details or explanations.The wrapping up of data and functions into a single unit is known as data encapsulation.


3. What is the Need for Static Members.
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. When you declare an object of a class having a static member, the static member is not part of the class object.

4. Define Polymorphism.
Polymorphism is another important oops concept. Polymorphism means the ability to take more than one form. For example, an operation may exhibit different behavior in different instances. Behavior depends upon the types of data used in the operation.

5. What do you mean by pure virtual functions?
A pure virtual member function is a member function that the base class forces derived classes to provide. Any class containing any pure virtual function cannot be used to create object of its own type.

6. What is function Prototype? 
A function prototype or function interface in C, Perl, PHP or C++ is a declaration of a function that omits the function body but does specify the function's return type, name and argument types. While a function definition specifies what a function does, a function prototype can be thought of as specifying its interface.

7. What is an identifier?
Identifiers are names for various programming elements in c++ program. such as variables, arrays, function, structures, union, labels ect., An identifier can be Composed only of uppercase, lower case letter, underscore and digits, but should start only with an alphabet or an underscore.

8. What is a keyword?
Keywords are word whose meanings have been already defined in the c compiler. They are also called as reserved words. For example main(), if, else, else, if, scanf, printf, switch, for, goto, while ect.,

9. Define data hiding.
The purpose of the exception handling mechanism is to provide a means to detect and report an “exceptional circumstance” so that appropriate action can be taken.

10. What is the use of scope resolution operator?
In C, the global version of the variable cannot be accessed from within the inner block. C++ resolves this problem by introducing a new operator :: called the scope resolution operator. It is used to uncover a hidden variable.Syntax: :: variable_name

11. When will you make a function inline?
When the function definition is small, we can make that function an inline function and can mainly go for inline function to eliminate the cost of calls to small functions.

12. What is overloading?

Overloading refers to the use of the same thing for different purposes. There are 2 types of overloading:
1. Function overloading
2. Operator overloading

13. What is the difference between normal function and a recursive function?
A recursive function is a function, which call it whereas a normal function does not. Recursive function can’t be directly invoked by main function.


Thanks
Mukesh Rajput
no image
Define the following terms : a) Actual parameters b) Formal parameters c) Global variables d) Local variables.

Actual parameters :  When a function is called from main program(calling function), the function call contains a list of data(variables) that are sent as input to the called function. Such data are called as actual parameters or actual arguments.
Example : x = test(p,q,r); where p,q,r are actual arguments

Formal parameters : The function header of a called function contains a list of data along with their data types. This list of data are known as formal parameters. The formal parameters receive their value from actual parameters.

a. The formal parameter values are available only as long as the function is being executed.
b. For every actual argument there must be a formal argument of the same data type.
c. Any changes made to the formal parameters in the called function do not change the actual parametersOnce the function is terminated the formal parameters are not available any more.
Example : int prod(int m, int n); //function header

Local variables : Local variables are the data declared within a user defined function and available only within that function.
Example :
int sum(int x, int y)
{
int r;
………
………
}

Global variables :  Global variables are the data that are declared before the main program and that are available to the main program as well as the functions that are called from the main program.

int p, r;
void main()
{
………
………
}


Thanks
Mukesh Rajput
no image
Online Compiler to compile computer program

At present so many online compiler are available for different language like C, C++, Java, Python, PHP, Ruby etc. to compile there program. These online compiler are very helpful for all the new programmer how want to start their programming. In this section we mentioned some online compiler which are very helpful for online compilation of the program.

List of different online compiler for C++ and many more languages:

1. https://www.jdoodle.com 
2. https://www.codechef.com
3. https://www.onlinegdb.com
4. http://cpp.sh/
5. https://gcc.godbolt.org
6. https://ideone.com
7. http://webcompiler.cloudapp.net/
8. https://repl.it/site/languages/cpp11
9. http://codepad.org
10. https://theonlinecompiler.com/ide
11. https://code.hackerearth.com



Thanks
Mukesh Rajput
no image
Logical Errors in C++ language : 

These types of errors depend on the logical thinking of the programmer during programming and are easy to detect if we follow the line of execution.

Listed below are some common programming errors: 

1. Commonly using ">" for ">>" and "<" for "<<".
2. Directly access the private variables of a class in main program.
3. Using switch statements without break.
4. Wrong usage of postfix and prefix operator in a program.
5. Using undeclared and uninitialized variables and functions in your program.
6. Include incorrect header files in your program.
7. Marking a member function as const in the class definition but not in the member function implementation. 
8. Trying to return a value in a void function in your program. 
9. Confusing the name of an array with the contents of the first element. 
10. Using "=" instead of "= =" (comparison operators).
11. Trying to divide a number by Zero.
12. Not using string functions and treating the strings are integer . 
13. C type string not terminated by '\0'- Null character.
14. Mismatched "{" or IF-ELSE statements or for that matter any looping statement.
15. using namespace std errors.


Thanks
Mukesh Rajput
no image
Introduction to Programming Errors

In C++ programming the errors are mistakes in the programming examples that cause the program to behave unexpectedly. Most of the well versed and experienced programmers also make these kinds of mistakes in their program. Basically, Programming error is known as Bugs and the process of removing these bugs are called as Debugging.
The most common errors can be broadly classified as follows:
1. Programming Errors: These types of errors are generated when typographical errors are made by users during there program code.For example, int  5 a; here, 5 is written as accidentally which further makes our program create an error during compilation. 
2. Compiler Errors: These types of errors detected by the compiler that makes the program un-compilable. For example, Int x;
3. Linker Errors: These are errors generated when the executable of the program cannot be generated. This may be due to wrong function prototyping, incorrect header files.
4. Execution Errors: These types of errors occur at the time of execution. Looping and arithmetic errors fall under this category.
5. Logical Errors: These types of errors depend on the logical thinking of the programmer and are easy to detect if we follow the line of execution.

Programming Example to show these errors:

#include<iostream>  
#include<math.h> 
using namespace std;
int main()
{
//programming error/ typographical errors because 5 is written accidentally by programmer 
int 5 x; 
// Compile time errors because float can not be written as Float.
Float ch;
// Linker Error because for clrscr() to work we need conio.h heaher file which is not used
clrscr();
//Execution Errors, because loop can not be properly used by the programmer it go infinitely
for( int i; i<=10 )
{
// statements


}
getch(); 
return 0;
}


Thanks
Mukesh Rajput
no image
Keywords which are commonly used in C++ programming:

Below are some keywords listed:

1. class – It is used for declaring/defining a class.
2. new – It is used to allocate storage on the free store space in computer system(heap).
3. delete – It is used to de-allocate the storage on the free store space in computer system.
// new and delete are more robust than the C library functions malloc and free.
4. inline – It is used for inline member functions.
5. private/protected/public – These are the access specifiers used for data hiding which is a means of protecting data of a class.
private – These types of data are not visible outside of the class.
protected – These types of data like private except visible only to derived classes through inheritance.
public – These types of data are visible to all applications.
try/throw/catch –  It is used in exception handling.
6. friend –  It is declares a class will full access rights to private and protected members of an outside class without being a member of that class.
7. explicit – It prevents implicit conversion of a data type to a particular class that may lead to unexpected surprises:
8. array::array(size_t n); creates an array with n elements.
9. float max(array const &a); a function that uses the array data type.
10. max(m); where m is an integer inadvertently passed to the function.  
// A new array of m elements will be implicitly created automatically, which is not what was intended.
virtual – a declaration specifier that invokes polymorphism on a function.

11. bool/false/true – used for Boolean logic.
bool – new data type that can only accept the values true and false.
false – numerically zero.
true – numerically one.


Thanks
Mukesh Rajput