C++ Programming Tutorial - Introduction to C++


Resources > C++ Quick Notes > {{currentSubTopic}}

Introduction to C++

Computer Programming :

A finite sequence of instructions given to the computer to do a specific task is called as a computer program. A group of programs is called as software. Programs can be classified into two distinct groups:
1) Application Programming
2) System Programming

Application Programming :

It carries out the specific processing required for the user’s application such as an accounting system or reservation of tickets. Precisely an application program directs the computer to resolve the user’s problem.

System Programming :

It is oriented towards the needs of the hardware and facilitates the development and running of applications. The most significant system software is the operating system.

Programming Languages :

A program communicates with the computer through a medium called programming language. Programming languages can be classified into two groups;

1. Low Level Languages
a. Machine Language
b. Assembly Language
2. High Level Languages
a. Procedural Language
b. Non-procedural Language

Low level Languages :

Low-level languages are machine dependent. Hence a program written in these languages is good for that particular machine.

Machine language :

Every computer has its own language. This is called machine language. It is a combination of 0’s & 1’s called as binary language. It varies from one machine to another. Machine language consists of cryptic instructions that control the computer’s internal circuitry. Computer understands only machine language.

Assembly language :

Since machine language is cryptic and it has cumbersome syntax, they replace the binary language by symbols (cg. ADD, SBU). This symbolic language is called as assembly language. In assembly language, mnemonics are used to represent operation codes and strings of characters are used to represent address. There is always a one to one correspondence between assembly language program and the equivalent machine language program. A program in assembly language, before its execution, s first translated in to machine language by a system program called assembly.

Since assembly language are machine dependent, the programs will be efficient.
It is machine dependent. Thus programs written in one machine cannot be portable to another machine.
As assembly language programmer must be an expert who knows all about the logical structure of the computer.
Writing assembly language program is difficult and time consuming.

High level language :

It contains very few of the machine dependent details. They can be used with little or no modification on a variety of computers. Before execution, a high level language program needs to be translated into machine language by a system program called compiler. The original program is called the source program and the translated file called as object program. These language are also called as problem oriented language.

Procedural Language :

In procedural language, to achieve a result, the user needs to provide detailed procedure. E.g. BASIC, FORTRAN, PASCAL, C.

Non–Procedural Language :

These are the language, which allow even a non– technical user to interact with the computer in a simpler and friendlier manner. The user needs not provide detailed procedure to get a result E.g. SQL.

Portability: High Level language are machine – independent. Thus a program written for one machine can be portable to another machine with less or no modification.
Easy debugging: Errors can be easily removed.
Easy software development: Software can be easily developed precisely & concisely.
Readability: Easily understandable and maintainable.
Since high – level languages have to be converted into machine language by the compiler, it takes more time for execution than the low level language.

Features of C++ :

C ++ has certain characteristics over other programming languages. The most remarkable ones are:

Object-oriented programming :

The object oriented programming allows the programmer to design applications from a point of view more like a communication between objects rather than on a structured sequence of code. In addition it allows a greater reusability of code in a more logical and productive way.
You can practically compile the same C++ code in almost any type of computer and operating system without making any changes. C++ is the most used and ported programming language in the world.

Brevity :

Code written in C++ is very short in comparison with other languages. Since the use of special characters is preferred to key words.

Modular Programming:

An applications body in C++ can be made up of several source code flies that are compiled separately and then linked together saving time since it is not necessary to recompile the complete application when making a single change but only the file that contains it. In addition, this characteristic allows to link C++ code with code produced in other languages, such as assembler or C++.

C Compatibility :

C++ is backwards compatible with the C language. Any code written in C can easily be included in a C++ program without making any change.

Speed :

The resulting code from a C++ compilation is very efficient, due to its duality is high–level and low–level language and to the reduced size of the language itself.

Simple Structure of a C++ Program :

//This is my first program
int main()
cout<<“Hello Welcome to C++”;
return 0;

Comments :

Comments are used in C++ programs the documentation so that it may be readable or understandable by other programmer. All comments are ignored by the compiler and have no effect on the way the program runs. It may appear anywhere in a program. Also any number of meaningful comments can be given.

Preprocessor Directive :

Lines in the program that begin with # are known as preprocessor directives. The preprocessor is a program that creates modified version of the C++ source program according to the directives supplied in the program. The modified program is then given to the compiler. Through the preprocessor directives, we can define constants (#define), include header files (#include), and add condition for compilation (#if...). The preprocessor directives should not end with a semicolon (;), whereas every other statement should end with a semicolon because the program statements are message to the computer whereas preprocessors are message to the compiler.
In this above program, we included #include<iostream.h> to instruct the compiler to include the file iostream.h before compilation because this header file contains all the declarations that are related with cout and << operator. The main difference between C and C++ is using preprocessor is that C relies more on it but C++ not much.

main ():

A function is a self – contained block of statements that performs the desired task. Object oriented C++ programs consists mostly of classes but there is always at least one C like function: main ( ). The execution of a program begins with main ( ) and it ends at the closing brace ( ) of it. The int value returned by main ( ) is the value returned to the operating system. If the value returned is 0, it is the message to the system that the program has completed successfully. If it is a non-zero value then it is an abnormal termination of the program.

Statements :

cout<<“Hello welcome to C++”; // is a statement.

A statement in C++, is a valid expression to perform the desired task. It ends with semicolon (;). A valid C++ statement, has to follow two rules: syntax and semantic. Syntax is related to the grammar of the language and semantic is the meaning or logic behind a word within a statement. A statement can he a declaration, assignment, expression or a function call.

Output Operation :

cout<<“Hello welcome to C++”;

This statement causes the string Hello welcome to C++ to he displayed on the screen. The identifier cout is a predefined object that represents the standard output stream in C++. It is the object of ostream class. The operator ‘<<’ is called as insertion or put to operator. The bit-wise left shift operator in C++ ‘<<’ is overloaded with the cout object. This causes the variable or a constant on the right-side of the insertion operator, to be inserted on the standard output device (screen). It is also possible to redirect the output to other devices. Every cout statement ends with a semicolon (;).

Cascading the output operator :

If we want to display variables and string constants together, we can cascade them.

char name [20] = “Rajeev”,
int age = l8;
cout << name << “is”<< “years old”;

Insertion operator :

int x;

This statement halts the execution of the program till we enter an integer and press the enter key. The number we have entered will be stored in the memory location x. It is similar to the scanf() statement in C. Here cin is the object of class istream. The class, istream, is associated with the standard input device (the key hoard). The ‘>>' (extraction operator) reads the value from the input device and placesit in the variable on its right side.cin operator can also be cascaded for different variables.

char name [20];
int age;

This statement requires two values, first one is of type string and the second one is of type int. After typing the name either we can press spacebar for the second value or the enter key. cin reads only one word. Therefore a blank space cannot be used between single values. While receiving a string cin does not take space. Hence if we enter amit khan, it displays only amit not khan.

cin>>name;    	:		amit khan
cout<<name;   	:		amit
While cascading the insertion or extraction operators, we cannot place semicolons in between.
cin>>name>>age; 	//invalid
cout<<name<<age; 	//invalid

endl operator :

The standard library provides set of functions for manipulating the input and output. These functions are called as manipulators. These manipulators insert an operation that modifies the state in between the object being read or written. endl is an Output Stream manipulator which creates a new line wherever it is placed.
cout<<“Welcome”<<end1<< “To C++”;

Naming Convention :

Turbo C++ is an IDE (Integrated Development Environment), used to create, compile and execute a C/ C++ program. To compile a C++ file, it should have .cpp extension (name.cpp). The name should be below 8 characters and it should not have any special symbol except underscore (_). The extension cpp is the only way o tell tile IDE to use the C ++ compiler.

Environment :

Text Editor :

Text Editor is an interface which helps us to type a program (file) enabling us to store and retrieve them from the secondary memory like floppy or hard-disk. The program we typed in the text editor is called as source program.

Pre-processor :

The line which begins with # is known as pre-processor directive or pre- processor statement. Pre-processor is a program that processes the source program before it passes it to the compiler. The processed program is called as expanded source code.

Compiler :

C++ compiler is a program which translates the expanded source code from high-level language to machine language. The machine code generated by the compiler is called is object code. The compiler acts as an interface between the user and the machine by converting the user language into machine language. The period taken to convert the source code into binary is called as compile time. Also the compiler traces the errors occurred in the program. The errors which are detected during the compile time are called as compile time error.

Linker :

Linker is a program winch links the standard libraries to the object code so as to build an executable program. By linking the object code with the standard libraries, we give a body to the standard function (e.g. cout) and thus it becomes an executable file.

Loader :

Loader is a program which takes input as the executable program generated by the linker and copies it into the memory (RAM) so that it starts executing. Usually, it is a part of operating system. Period of loading and preparing the object code is called as load time.

IDE: (Integrated Development Environment)

IDE is software that enables the user to create, edit, compile and execute a program. The IDE is completely menu driven, which are known as dialogue boxes. Through dialogue boxes it becomes easier to edit, compile and run the program. These environments also display the errors, it detected. We need to rectify these errors and compile them again (Turbo C++ is a powerful IDE).

Errors :

In programming, errors are known as bugs since they seem to creep undetected into every program. The process of finding and eliminating the bugs is known as debugging. The errors can be classified into three categories: compile line error, linker error and runtime error.

Compile time error :

The statements of a program are scanned during compilation process. The errors detected by the compiler are called compilation errors.
The compile time error can be classified into three:

If a syntax error or semantic error is detected, the compiler continues the process in order to detect further errors. But it does not create the object files. An error that prevents the compiler to produce the object code is known as fatal error. But a warning does not prevent the object file from being produced.

Linker Error :

It is possible to have an error during the linking process. For example, if a function is declared in a program and if it is not defined, the function call creates an error during the linking time because during compilation, the compiler matches the function call with the function declaration not with the definition, but for the linker it needs the function definition.

Run time / Logical Error :

Logical errors are the errors caused by an incorrect algorithm or mistyped statements. It is untraceable by the compiler. With these errors the compilers produce the compiled file, but it may produce wrong results during the runtime. These errors are much more harmful than the syntax & semantic errors.

Algorithm :

A finite sequence of unambiguous instructions to solve a problem is called is algorithm. Algorithm has the following five characteristics:
1) Input: An algorithm begins with instructions to accept inputs. These inputs are processed by the subsequent instructions in the algorithm.
2) Definiteness: The processing rules specified in the a algorithm must be precise and unambiguous. In other words, the instruction must not be vague.
3) Effectiveness: Each instruction must be sufficiently basic (division, multiplication, addition, etc.) such that it is carried out in finite time by a person with paper and pencil.
4) Finiteness: The total time to carry out all the steps in the algorithm must be finite. Even if it contains repetitive statements, the repetition must be finite.
5) Output: An algorithm must produce one or more outputs.
Algorithm to find the average number of vowels in a passage :

Planning of a program :

A program can be planned with two approaches
1. Top – down Programming
2. Bottom – up Programming
Top – Down Programming :
In this approach, first we develop an outline of the program consisting of phrases or sentences. This is simply known as algorithm. The algorithm could be written in a partial programming language, known as pseudo code. Once the overall program strategy is defined, the details associated with the individual statements are considered and implemented using programming language.
Disadvantages :
1. It generates modules that are specific to the application, not very reusable.
2. It complicates the testing because no executable file exists until the code is developed.
3. Since the development is based on the algorithm, if there is a change in the concept, everything needs to be re-written.
4. In this style, most of the time the data is globally exposed, hence there exists a dependency between different parts of the applications.
Bottom-up Programming :
In this approach, the application is developed gradually. With the help of existing primitive modules (functions) the more complicated features are developed. The development continues until the entire application has been written down.
Advantages :
1. More reusable modules are generated.
2. Testing becomes simpler because of the existing modules.
3. Maintenance and up–gradation become simpler

A block diagram of a computer :

Data types, Keywords and Variables


Keywords are the special words, which are designed to do a specific task and whose meaning is already known to the compiler. Since it is predefined, it cannot be used as identifiers. These words are also known as reserved words. Many of them are common to both C and C++.


Name of variables, symbolic constants, functions, arrays, classes is called as identifiers. The predefined identifiers are known as keywords. The following rules have to be followed white naming an identifier:
1. It may be the combination of alphabets, digits and underscore.
2. No special characters such as blank space, semicolon is allowed in the name except underscore.
3. Keyword cannot be used as an identifier.
4. Identifiers are case sensitive.

Note: Difference between C and C++ in naming the identifiers is the limit on the length. In C the identifiers should be less than 32 characters whereas C++ places no limit on the identifier’s size.


A Constant is an entity whose value does not change during program execution. Most commonly used constants are character, integer, float, logical and string constants.

Integer Constant:

An integer constant consists of one or more digits. It can be either positive or negative. The default sign is positive. The range of the integer constant is – 32768 to +32767.(eg 783, + 123, -433)
Unsigned integer constant – 123U
Long Integer Constant – 123L.

Floating Point Constant:

A floating point constant is a number that has a decimal point. It is also called as real constant. Floating numbers are internally broken into two parts fractional portion and exponent portion. Both are stored in the binary form. Floating point constant can be written in two forms, i.e. fractional form and exponential form.

Fractional form:

A float constant is a number that has a whole part of the number, followed by decimal point, followed by a series of digits representing the fractional part. It can be either positive or negative. If no sign precedes then it is considered as positive. e.g. 77345.25433

Exponential form:

In the exponential form, the float constant is represented in two parts. The part appearing before ‘e’ is called mantissa and the number after the ‘e’ is called exponent. This is also called as scientific form. e.g. 8.5el2, 8.5E12

Character Constant:

A character constant is a single character enclosed in single quotes (apostrophes). e.g. ‘a’, ‘@’

Wide Character Constant:

ANSI C++ has introduced a new data type called wchar_t, which accepts all the international language characters. These characters cannot be fit into one byte. They are 16 bit characters (2 bytes). The Wide Character constant begins with L. They are also known as Unicode characters. E.g. L ‘ab’

Logical constant:

A logical constant is either zero or non-zero. If it is zero, the evaluation of the condition is false. If it is non-zero then it is true. The bool data type takes 1 as true and 0 as false.

String Constant:

A collection of characters enclosed in double quotes is called as string constant. A string constant is stored in an adjacent memory location.

Data Types:

Data is piece of information. In C++ we can store the following types of data. Data types can be classified into two groups:


Variable is a memory location to store a data, referred by a symbolic name. The data may or may not vary during the program execution. The data item must be assigned to the variable at some point in the program. The assignment of value to the variable is called as initialization or assignment. After the assignment, the data can be accessed or manipulated at some point of the program by simply referring the variable name.

A variable has to be declared before it is used. By declaring the variable, memory space is allocated to that variable. A variable declaration consists of an optional storage class, optional type
modifier, data type and the variable name and optional initialization. static unsigned int basic=10;

Where static is a storage class, unsigned is a type modifier, int is the data type and basic is the variable name, and 10 is the assigned value to the variable basic through the assignment operator(=). The data type can be any of the primary data type such as char, int, float and double or secondary data type such as arrays, pointers, structure, union and enumeration. With a single data type we can declare multiple variable names separated by comma.
int basic, gross, bonus;

Reference Variables:

Reference is an alternate name for an object or a variable in C++. i.e. reference variables are alternate names (alias) for previously defined variables.

float f=10;
float &x=f;
cout<< “f=”<<f;
cout<< “x=”<<x;
Output: f=25 x=85

Here x is called as a reference variable referring to f. Whenever we make a change to x or f, it is reflected on each other.

& is not an address operator. The notation ‘float&’ means reference to float.
Where x is going to refer the same base address of f.

Output: Same base address.

All reference variables should be initialized at the time of declaration.

int x=&a; //valid
int &y; // Error (y must be initialized)
extern int &z; //valid (which refers z is initialized elsewhere)

The value of the reference cannot be changed alter initialization.

int a=10;
int &x=a;
x++; //It change the value of ‘a’ to 11 not its base address.


Operators are special symbols, which represent a particular operation that can be performed on some data. The data is called as operand.
e.g. 8 + 5 – 7.
Here 8, 5, 7 are called operands and +, – are called operators.

Depending upon the number of operands and its functions, the operators can be classified into five groups:
1. Unary Operator,
2. Binary Operator,
3. Ternary Operator,
4. Selection operator

Unary Operator

Unary in literal terms is single. These operators need one operand to perform an operation. Therefore it is called as a unary operator.

Binary Operator

Binary in literal terms is two. To perform an operation, these operators need two operands. Therefore they are called as binary operators.

Arithmetic Operator

Arithmetic operators are used to perform mathematical operations.

Relational Operator

Relational operators are used to compare two operands to check whether the first one is greater/less/equal/unequal than the second. The result of a Boolean expression is either true or false.

Logical Operators

Logical operators are those operators that are applied to the logical expression. The output of the expression will be either true or false.

Bitwise Operator

An Operator that permits the programmer to access and manipulate individual bit of a data are called as bitwise operators. Among the bitwise operators, ones complement is unary.

Assignment Operator

The assignment operator has single equal sign = . All the arithmetic operators can be combined with assignment operator & can be made compound operator.

Note that the difference between simple and compound assignment operator is that, compound operator does not make temporary variables during operations.
All the binary operators except relational operators can be combined with assignment operators.

Ternary Operator

?: which takes three operands, therefore it is called as ternary operator.
The memory operator has the following operator formation:
condition? expression1 : expression2

First, the condition is evaluated. If the condition is true then expression1 will be carried out and the result is returned, else expression2 will be carried out. The expression can be simple or compound or it can be another ternary operator. This is also called as conditional operator.

Selection Operator


Inheritance is a concept by which the properties of a class are available to another. It allows the new classes to be built from the older instead of being rewritten from scratch. The class that is being inherited (parent) is called as the superclass or the base class. The class that inherits (child) properties and function of another class is called the subclass or the derived class.

The derived class inherits all the properties of the base class and can add properties of its own but, the base class remains unchanged when it is inherited. Thus Inheritance allows us to reuse existing code, without modifying the original, which is called as reusability.

Member access specifier / control visibility

An access control defines a boundary to a member of a class. They are also known as visibility labels or access specifiers. A class can have three kinds of access control.

1. private:

Member of a class is accessible only by members and friends of the class. By default all the members of the class are private.

2. protected:

Member of a class is accessible only by members and friends of the derived classes. Hence, by using protected, we can create class members that are private to the class but still be inherited and accessed by the derived class. When derived class is used as a base class for another derived class, any protected member can be accessed by the second derived class.

3. public:

Member of a class is accessible by any function in the application.

Forms of Inheritance (Types)

A class can inherit the properties of one or more than one class or from more than one level. Depending on the number of base classes and their form, Inheritance is classified into five distinct groups.
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

Single Inheritance

If a derived class has only one base class then, it is called as single inheritance. All the public and protected properties of the base class are accessible in the derived class.

Multilevel Inheritance

When a derived class becomes a base class to another class it is known as multilevel inheritance. In the figure, class B is derived from A and class B serves as a base class to the derived class C. Here class B is known as intermediate base class because it provides a link between A and C. Hence the properties of A are available in C.

Multiple Inheritance

When a derived class has more than one base class, the class has all the properties of the base class. This form of inheritance is known as multiple inheritance. Thus multiple inheritance allows us to combine several exciting classes without depending on a common base class.

Here each base class can be inherited with any visibility mode but a comma must separate each base class. Here, C has all the protected arid public properties of A and B.

Hybrid / Multipath Inheritance

When a derived class (derived3) has two or more base classes (derived1, derived2) which are derived from a common base class (base) then multiple copies of the base class are available in the last (newly) derived class (derived3). Hence a member of a base class is invoked either in the derived class (derived class derived3)) or invoked with an object of derived3, there occurs an ambiguity between the copies coming from derived1 and derived2. The ambiguity can be prevented by declaring the base classes as virtual when it is inherited. This can he accomplished by declaring the base class name with the keyword virtual. Hence the compiler allows only one copy of the base class members in the derived class (derived3).

Classes and Objects

Structure of a C++ program with class

//Global declarations if any
class abc //Declaring new data type abc
	int x, y;			// Data members
	public:			// Access control
	void getdata ()		// Member function
	void putdata ()

int main ()
	abc obj;			// abcis the data type name (class name) and obj is the object name.
	obj.getdata ();
	obj .putdata ();		// calling the member function with object obj
	return 0;


A class is a user defined data type; it is a fundamental packaging unit of OOPs technology. The programming construct of class, binds the data (state) and function (services) with a cohesive concept to produce a group of similar objects. It also allows the data and function to be hidden, if necessary, from external use. Class is called as a template of an object. Class is also called as definition for an abstract data type.


An object is an independent software entity, which combines data and the functions. It has its own lifetime, internal data and the set of functions to operate on the data. They are born (constructed), live a full and productive life and die (destroyed). The fundamental purpose of an object is to provide one or more services. This means that the other objects can delegate work to them instead of having to do everything for themselves.

An object is an instance of a class (The instance of the structure is called as variable and the instance of the class is called as object). An object created is like any other built-in-type variable. Once the class has been declared, we can create a variable of that type using the class name. abc obj; // abc is the class name and obj is called as an object.

Class Members

A class can have two kinds of members
1. Data members.
2. Member functions

Data Members

All the primary (int, float, char, double, bool) and the secondary data types (arrays, pointers, structures variables. union variables and class objects) can be the data member of class. Data Members can be classified into two groups
1. regular (auto)
2. static

1. regular (non-static):

When an object is created, every object gets a copy of all the regular members of the class. In the above example x, y are the data members. All the objects will have a copy of x and y.

2. static:

Only one copy of static variable is created. All the objects share the same copy of the variable. In general all the data members remain in the private part of the class.

Member Functions

A function that is defined inside a class declaration is called as member function. In general all the member functions are defined in the public area of the class. It can also be defined in the private area, then, only the member function of the class can access the private member function. Member functions are also called as methods.