Chap1 Intro To OOP C++

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

C++ Programming

What is C++
C++ is a general purpose, case-sensitive, free-form programming language that supports object-oriented,
procedural and generic programming. C++ is a middle-level language, as it encapsulates both high and
low level language features.

Object-Oriented Programming (OOPs)


C++ supports the object-oriented programming, the four major pillar of object-oriented programming
(OOPs) used in C++ are:
1. Inheritance
2. Polymorphism
3. Encapsulation
4. Abstraction

C++ Standard Libraries


Standard C++ programming is divided into three important parts:
 The core library includes the data types, variables and literals, etc.
 The standard library includes the set of functions manipulating strings, files, etc.
 The Standard Template Library (STL) includes the set of methods manipulating a data structure.

Usage of C++
By the help of C++ programming language, we can develop different types of secured and robust
applications:
 Window application
 Client-Server application
 Device drivers
 Embedded firmware etc

C++ Program
In this tutorial, all C++ programs are given with C++ compiler so that you can easily change the C++
program code.
File: main.cpp
1. #include <iostream>
2. using namespace std;
3. int main() {
1|Page
4. cout << "Hello C++ Programming";
5. return 0;
6. }

C vs. C++
What is C?
C is a structural or procedural oriented programming language which is machine-independent and
extensively used in various applications.
C is the basic programming language that can be used to develop from the operating systems (like
Windows) to complex programs like Oracle database, Git, Python interpreter, and many more. C
programming language can be called a god's programming language as it forms the base for other
programming languages. If we know the C language, then we can easily learn other programming
languages. C language was developed by the great computer scientist Dennis Ritchie at the Bell
Laboratories. It contains some additional features that make it unique from other programming
languages.

What is C++?
C++ is a special-purpose programming language developed by Bjarne Stroustrup at Bell Labs circa
1980. C++ language is very similar to C language, and it is so compatible with C that it can run 99% of
C programs without changing any source of code though C++ is an object-oriented programming
language, so it is safer and well-structured programming language than C.

The following are the differences between C and C++:


 Definition
C is a structural programming language, and it does not support classes and objects, while C++
is an object-oriented programming language that supports the concept of classes and objects.
 Type of programming language
C supports the structural programming language where the code is checked line by line, while
C++ is an object-oriented programming language that supports the concept of classes and
objects.
 Developer of the language
Dennis Ritchie developed C language at Bell Laboratories while Bjarne Stroustrup developed
the C++ language at Bell Labs circa 1980.
 Subset
C++ is a superset of C programming language. C++ can run 99% of C code but C language
cannot run C++ code.
 Type of approach
C follows the top-down approach, while C++ follows the bottom-up approach. The top-down
2|Page
approach breaks the main modules into tasks; these tasks are broken into sub-tasks, and so on.
The bottom-down approach develops the lower level modules first and then the next level
modules.
 Security
In C, the data can be easily manipulated by the outsiders as it does not support the encapsulation
and information hiding while C++ is a very secure language, i.e., no outsiders can manipulate its
data as it supports both encapsulation and data hiding. In C language, functions and data are the
free entities, and in C++ language, all the functions and data are encapsulated in the form of
objects.
 Function Overloading
Function overloading is a feature that allows you to have more than one function with the same
name but varies in the parameters. C does not support the function overloading, while C++
supports the function overloading.
 Function Overriding
Function overriding is a feature that provides the specific implementation to the function, which
is already defined in the base class. C does not support the function overriding, while C++
supports the function overriding.
 Reference variables
C does not support the reference variables, while C++ supports the reference variables.
 Keywords
C contains 32 keywords, and C++ supports 52 keywords.
 Namespace feature
A namespace is a feature that groups the entities like classes, objects, and functions under some
specific name. C does not contain the namespace feature, while C++ supports the namespace
feature that avoids the name collisions.
 Exception handling
C does not provide direct support to the exception handling; it needs to use functions that
support exception handling. C++ provides direct support to exception handling by using a try-
catch block.
 Input/Output functions
In C, scanf and printf functions are used for input and output operations, respectively, while in
C++, cin and cout are used for input and output operations, respectively.
 Memory allocation and de-allocation
C supports calloc() and malloc() functions for the memory allocation, and free() function for the
memory de-allocation. C++ supports a new operator for the memory allocation and delete
operator for the memory de-allocation.
 Inheritance
Inheritance is a feature that allows the child class to reuse the properties of the parent class. C
language does not support the inheritance while C++ supports the inheritance.
 Header file
C program uses <stdio.h> header file while C++ program uses <iostream.h> header file.

3|Page
Let's summarize the above differences in a tabular form.
N C C++
o.
1) C follows the procedural style C++ is multi-paradigm. It supports both
programming. procedural and object oriented.
2) Data is less secured in C. In C++, you can use modifiers for class members
to make it inaccessible for outside users.
3) C follows the top-down approach. C++ follows the bottom-up approach.
4) C does not support function overloading. C++ supports function overloading.
5) In C, you can't use functions in structure. In C++, you can use functions in structure.
6) C does not support reference variables. C++ supports reference variables.
7) In C, scanf() and printf() are mainly used C++ mainly uses stream cin and cout to perform
for input/output. input and output operations.
8) Operator overloading is not possible in C. Operator overloading is possible in C++.
9) C programs are divided into procedures C++ programs are divided into functions and
and modules classes.
10 C does not provide the feature of C++ supports the feature of namespace.
) namespace.
11 Exception handling is not easy in C. It has C++ provides exception handling using Try and
) to perform using other functions. Catch block.
12 C does not support the inheritance. C++ supports inheritance.
)

C++ history
History of C++ language is interesting to know. Here we are going to discuss brief history of C++
language.
C++ programming language was developed in 1980 by Bjarne Stroustrup at bell laboratories of
AT&T (American Telephone & Telegraph), located in U.S.A.
Bjarne Stroustrup is known as the founder of C++ language.

It was develop for adding a feature of OOP (Object Oriented Programming) in C without
significantly changing the C component.
C++ programming is "relative" (called a superset) of C, it means any valid C program is also a valid
C++ program.
Let's see the programming languages that were developed before C++ language.
Language Year Developed By
Algol 1960 International Group
BCPL 1967 Martin Richard
B 1970 Ken Thompson
4|Page
Traditional C 1972 Dennis Ritchie
K&RC 1978 Kernighan & Dennis
Ritchie
C++ 1980 Bjarne Stroustrup

C++ Features
C++ is object oriented programming language. It provides a lot of features that are given below.

1) Simple
C++ is a simple language in the sense that it provides structured approach (to break the problem into
parts), rich set of library functions, data types etc.

2) Machine Independent or Portable


Unlike assembly language, c programs can be executed in many machines with little bit or no change.
But it is not platform-independent.

3) Mid-level programming language


C++ is also used to do low level programming. It is used to develop system applications such as kernel,
driver etc. It also supports the feature of high level language. That is why it is known as mid-level
language.

4) Structured programming language


C++ is a structured programming language in the sense that we can break the program into parts using
functions. So, it is easy to understand and modify.

5) Rich Library
C++ provides a lot of inbuilt functions that makes the development fast.

6) Memory Management
It supports the feature of dynamic memory allocation. In C++ language, we can free the allocated
memory at any time by calling the free() function.

7) Speed
The compilation and execution time of C++ language is fast.

8) Pointer
C++ provides the feature of pointers. We can directly interact with the memory by using the pointers.
We can use pointers for memory, structures, functions, array etc.

5|Page
9) Recursion
In C++, we can call the function within the function. It provides code reusability for every function.

10) Extensible
C++ language is extensible because it can easily adopt new features.

11) Object Oriented


C++ is object oriented programming language. OOPs makes development and maintenance easier
where as in Procedure-oriented programming language it is not easy to manage if code grows as project
size grows.

12) Compiler based


C++ is a compiler based programming language, it means without compilation no C++ program can be
executed. First we need to compile our program using compiler and then we can execute our program.

C++ Program
Before starting the abcd of C++ language, you need to learn how to write, compile and run the first
C++ program.
To write the first C++ program, open the C++ console and write the following code:
1. #include <iostream.h>
2. #include<conio.h>
3. void main() {
4. clrscr();
5. cout << "Welcome to C++ Programming.";
6. getch();
7. }
#include<iostream.h> includes the standard input output library functions. It provides cin and cout
methods for reading from input and writing to output respectively.

#include <conio.h> includes the console input output library functions. The getch() function is
defined in conio.h file.
void main() The main() function is the entry point of every program in C++ language. The void
keyword specifies that it returns no value.
cout << "Welcome to C++ Programming." is used to print the data "Welcome to C++
Programming." on the console.
getch() The getch() function asks for a single character. Until you press any key, it blocks the screen.

6|Page
C++ Basic Input/Output
C++ I/O operation is using the stream concept. Stream is the sequence of bytes or flow of data. It
makes the performance fast.
If bytes flow from main memory to device like printer, display screen, or a network connection, etc,
this is called as output operation.
If bytes flow from device like printer, display screen, or a network connection, etc to main memory,
this is called as input operation.

I/O Library Header Files


Let us see the common header files used in C++ programming are:
Header Function and Description
File
<iostream> It is used to define the cout, cin and cerr objects, which correspond to standard output
stream, standard input stream and standard error stream, respectively.
<iomanip> It is used to declare services useful for performing formatted I/O, such as setprecision
and setw.
<fstream> It is used to declare services for user-controlled file processing.

Standard output stream (cout)


The cout is a predefined object of ostream class. It is connected with the standard output device, which
is usually a display screen. The cout is used in conjunction with stream insertion operator (<<) to display
the output on a console
Let's see the simple example of standard output stream (cout):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. char ary[] = "Welcome to C++ tutorial";
5. cout << "Value of ary is: " << ary << endl;
6. }
Output:
Value of ary is: Welcome to C++ tutorial

7|Page
Standard input stream (cin)
The cin is a predefined object of istream class. It is connected with the standard input device, which is
usually a keyboard. The cin is used in conjunction with stream extraction operator (>>) to read the input
from a console.
Let's see the simple example of standard input stream (cin):

1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. int age;
5. cout << "Enter your age: ";
6. cin >> age;
7. cout << "Your age is: " << age << endl;
8. }
Output:
Enter your age: 22
Your age is: 22

Standard end line (endl)


The endl is a predefined object of ostream class. It is used to insert a new line characters and flushes
the stream.
Let's see the simple example of standard end line (endl):
1. #include <iostream>
2. using namespace std;
3. int main( ) {
4. cout << "C++ Tutorial";
5. cout << " Javatpoint"<<endl;
6. cout << "End of line"<<endl;
7. }
Output:
C++ Tutorial Javatpoint
End of line

8|Page
C++ Variable
A variable is a name of memory location. It is used to store data. Its value can be changed and it can be
reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Let's see the syntax to declare a variable:

1. type variable_list;
The example of declaring variable is given below:
1. int x;
2. float y;
3. char z;
Here, x, y, z are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
1. int x=5,b=10; //declaring 2 variable of integer type
2. float f=30.8;
3. char c='A';

Rules for defining variables


A variable can have alphabets, digits and underscore.
A variable name can start with alphabet and underscore only. It can't start with digit.
No white space is allowed within variable name.
A variable name must not be any reserved word or keyword e.g. char, float etc.
Valid variable names:
1. int a;
2. int _ab;
3. int a30;
Invalid variable names:
1. int 4;
2. int x y;
3. int double;

9|Page
C++ Data Types
A data type specifies the type of data that a variable can store such as integer, floating, character etc.

There are 4 types of data types in C++ language.


Types Data Types
Basic Data Type int, char, float, double, etc
Derived Data Type array, pointer, etc
Enumeration Data Type enum
User Defined Data Type structure

Basic Data Types


The basic data types are integer-based and floating-point based. C++ language supports both signed
and unsigned literals.

The memory size of basic data types may change according to 32 or 64 bit operating system.
Let's see the basic data types. It size is given according to 32 bit OS.

Data Types Memory Size Range


char 1 byte -128 to 127
signed char 1 byte -128 to 127
unsigned char 1 byte 0 to 127
short 2 byte -32,768 to 32,767
signed short 2 byte -32,768 to 32,767
unsigned short 2 byte 0 to 32,767
int 2 byte -32,768 to 32,767
signed int 2 byte -32,768 to 32,767
unsigned int 2 byte 0 to 32,767
short int 2 byte -32,768 to 32,767
signed short int 2 byte -32,768 to 32,767
unsigned short int 2 byte 0 to 32,767
long int 4 byte
signed long int 4 byte
unsigned long int 4 byte
float 4 byte
double 8 byte
long double 10 byte
10 | P a g e
C++ Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name etc. A list of 32
Keywords in C++ Language which are also available in C language are given below.
auto break case char const continue default do
double else enum extern float for goto if
int long register return short signed sizeof static
struct switch typedef union unsigned void volatile while

A list of 30 Keywords in C++ Language which are not available in C language are given below.
asm dynamic_cast namespace reinterpret_cast bool
explicit new static_cast false catch
operator template friend private class
this inline public throw const_cast
delete mutable protected true try
typeid typename using virtual wchar_t

C++ Operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C language.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operator
 Unary operator
 Ternary or Conditional Operator
 Misc Operator

11 | P a g e
Precedence of Operators in C++
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to left.

Let's understand the precedence by the example given below:


1. int data=5+10*10;
The "data" variable will contain 105 because * (multiplicative operator) is evaluated before + (additive
operator).
The precedence and associativity of C++ operators is given below:
Category Operator Associativity
Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* & sizeof Right to left
Multiplicative */% Left to right
Additive +- Right to left
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == !=/td> Right to left
Bitwise AND & Left to right
12 | P a g e
Bitwise XOR ^ Left to right
Bitwise OR | Right to left
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right

C++ Identifiers
C++ identifiers in a program are used to refer to the name of the variables, functions, arrays, or other
user-defined data types created by the programmer. They are the basic requirement of any language.
Every language has its own rules for naming the identifiers.
In short, we can say that the C++ identifiers represent the essential elements in a program which are
given below:
 Constants
 Variables
 Functions
 Labels
 Defined data types
Some naming rules are common in both C and C++. They are as follows:

 Only alphabetic characters, digits, and underscores are allowed.


 The identifier name cannot start with a digit, i.e., the first letter should be alphabetical. After the
first letter, we can use letters, digits, or underscores.
 In C++, uppercase and lowercase letters are distinct. Therefore, we can say that C++ identifiers
are case-sensitive.
 A declared keyword cannot be used as a variable name.
For example, suppose we have two identifiers, named as 'FirstName', and 'Firstname'. Both the
identifiers will be different as the letter 'N' in the first case in uppercase while lowercase in second.
Therefore, it proves that identifiers are case-sensitive.

Valid Identifiers
The following are the examples of valid identifiers are:
1. Result
2. Test2
3. _sum
4. power

13 | P a g e
Invalid Identifiers
The following are the examples of invalid identifiers:
1. Sum-1 // containing special character '-'.
2. 2data // the first letter is a digit.
3. break // use of a keyword.
Note: Identifiers cannot be used as the keywords. It may not conflict with the keywords, but it is
highly recommended that the keywords should not be used as the identifier name. You should
always use a consistent way to name the identifiers so that your code will be more readable and
maintainable.
The major difference between C and C++ is the limit on the length of the name of the variable. ANSI C
considers only the first 32 characters in a name while ANSI C++ imposes no limit on the length of the
name.
Constants are the identifiers that refer to the fixed value, which do not change during the execution of a
program. Both C and C++ support various kinds of literal constants, and they do have any memory
location. For example, 123, 12.34, 037, 0X2, etc. are the literal constants.
Let's look at a simple example to understand the concept of identifiers.
1. #include <iostream>
2. using namespace std;
3. int main()
4. {
5. int a;
6. int A;
7. cout<<"Enter the values of 'a' and 'A'";
8. cin>>a;
9. cin>>A;
10. cout<<"\nThe values that you have entered are : "<<a<<" , "<<A;
11. return 0;
12. }
In the above code, we declare two variables 'a' and 'A'. Both the letters are same but they will behave as
different identifiers. As we know that the identifiers are the case-sensitive so both the identifiers will
have different memory locations.
Output

14 | P a g e
What are the keywords?
Keywords are the reserved words that have a special meaning to the compiler. They are reserved for a
special purpose, which cannot be used as the identifiers. For example, 'for', 'break', 'while', 'if', 'else',
etc. are the predefined words where predefined words are those words whose meaning is already
known by the compiler. Whereas, the identifiers are the names which are defined by the programmer to
the program elements such as variables, functions, arrays, objects, classes.
Differences between Identifiers and Keywords
The following is the list of differences between identifiers and keywords:
Identifiers Keywords
Identifiers are the names defined by the programmer Keywords are the reserved words whose
to the basic elements of a program. meaning is known by the compiler.
It is used to identify the name of the variable. It is used to specify the type of entity.
It can consist of letters, digits, and underscore. It contains only letters.
It can use both lowercase and uppercase letters. It uses only lowercase letters.
No special character can be used except the It cannot contain any special character.
underscore.
The starting letter of identifiers can be lowercase, It can be started only with the lowercase
uppercase or underscore. letter.
It can be classified as internal and external It cannot be further classified.
identifiers.
Examples are test, result, sum, power, etc. Examples are 'for', 'if', 'else', 'break', etc.

15 | P a g e

You might also like