BasicsOfCPP
BasicsOfCPP
Introduction
• Combination of Simula67 (Object oriented
language) and C
• Adds the concepts of classes, inheritance, function
overloading and operator overloading
• Being object oriented, large programs can be built
with clarity, extensibility and ease of maintenance
• Changed C from top-down structured language to
bottom-up object oriented language
Compiling and Running
• g++ command is used to compile C++ program
• It generates exe file which can be directly executed
• See HelloWorld.cpp
Output operator
• cout – predefined object that represents standard
output stream in C++
• << - insertion or put to operator, inserts contents of
variable on the right to the object on the left
• E.g. cout << var_name;
• << is also a bit-wise left-shift operator. This is
operator overloading (same symbol, multiple uses)
• Cascading: cout<<“Name=“<<name;
• First “Name=“ is sent to cout, then content of name
variable
Output operator
Input operator
• cin – predefined object that represents standard
input stream in C++
• >> - extraction or get from operator, extracts value
from the keyboard and assigns it to the variable on
the right
• E.g. cin >> var_name;
• >> is also a bit-wise right-shift operator. This is
operator overloading (same symbol, multiple uses)
• Cascading: cin >> n1 >> n2;
• If 2 values are input, 1st is assigned to n1, 2nd to n2
• See SumAverage.cpp
Input operator
iostream
• iostream is a header file containing declaration for
input output statements like cout, <<, cin, >>, etc.
• Old versions use iostream.h. ANSI C++ uses
iostream
namespace
• Introduced by ANSI C++ standards committee
• Defines scope for identifiers
• Identifiers can be used as
– <namespace>::<identifier>
OR
– using namespace <namespace>
– <identifier>
Keywords
• Reserved words, cant be used as variable names
Identifiers
• Names of variables, functions, arrays, classes, etc.
• Rules:
– Only alphabetic characters, digits and underscores are permitted.
– The name cannot start with a digit.
– Uppercase and lowercase letters are distinct.
– A declared keyword cannot be used as a variable name.
• ANSI C recognized only first 32 characters of
identifier, whereas no limit in ANSI C++
Constants
• Values that don’t change during execution
• Integers, Floating point numbers, characters, strings
– 123 // decimal integer
– 12.34 // floating point integer
– 037 // octal integer
– 0X2 // hexadecimal integer
– "C++" // string constant
– 'A' // character constant
– L'ab' // wide-character constant
• wchar_t is wide character literal for wide character
set which can’t be fit in one byte
• C++ also supports backslash char constants as in C
Basic Data Types
Basic Data Types
void Data Type
• To specify return type of a function not returning
any value
• To indicate empty argument list to a function
– E.g. void f1(void);
• To declare generic pointer
– E.g. void *gp;
– int * ip;
– gp = ip; // Valid statement
– ip = gp; // Invalid statement
– ip = (int *) gp; // Valid statement
• See VoidPointer.cpp
User Defined Data Types
• structures
• union
• class
• enumeration
structure
• Standalone primitive types are not sufficient for real
world problems
• structure and union are used to group logically
related data together of dissimilar data types
• Arrays group similar data type elements
struct <struct_name>
{
datatype member1;
datatype member2;
};
• See SampleStruct.cpp
union
• Similar to structure in grouping dissimilar data types
• struct size is equal to sum of sizes
• union size is equal to size of its largest element
• E.g.
union result
{
int marks; // 2 bytes
char grade; // 1 byte
float percent;// 4 bytes
};
• Variable of above union occupies 4 bytes, not 7
• See SampleUnion.cpp
struct vs union
Struct Union
A structure is defined with ‘struct’ keyword. A union is defined with ‘union’ keyword.
All members of a structure can be The members of a union can be
manipulated simultaneously. manipulated only one at a time.
The size of a structure object is equal to the The size of a union object is equal to the
sum of the individual sizes of the member size of largest member object.
objects.
Structure members are allocated distinct Union members share common memory
memory locations. space for their exclusive usage.
Structures are not considered as memory Unions are considered as memory
efficient in comparison to unions. efficient particularly in situations when
the members are not required to be
accessed simultaneously.
Structures in C++ behave just like a class. Unions retain their core functionality in
Almost everything that can be achieved C++ with slight add-ons like declaration
with a class can also be done with them. of anonymous unions.
class
• Another user defined data type
• Variables of classes are called objects
enumeration
• Allows attaching names to numbers improving
readability
• Syntax: enum shape{circle, square, triangle};
• Default values assigned are 0, 1, 2… and so on
• See SampleEnum.cpp
Symbolic Constants
• const int size = 10;
• Size is constant and its value cannot be modified
• They have to be initialized, they don’t have any
default value
• In C++ they are local variables, unlike in C where
they are visible outside the file
• enum {a,b,c} is equivalent to below
– const a = 0; // data type defaults to int
– const b = 1;
– const c = 2;
Storage Classes
• Specifies lifetime and visibility of variable
• See SampleStorageClass.cpp
Derived Data types
• Arrays: Same as C, the only difference is char array
should have size one more than the number of
characters. E.g. char arr[4]=“abc”;
• Functions: Discussed later
• Pointers: Same as C
Type Compatibility
• int, short int, long int are treated differently
• char, unsigned char, signed char are treated
differently
• In C, sizeof(‘a’) is equal to sizeof(int)
• In C++, sizeof(‘a’) is equal to sizeof(char)
Declaration & dynamic initialization of
variables
• Same as C
Reference Variables
• Can be used as function parameter, function return
value, standalone reference variable
• C only supports it using pointer (address of variable)
• C++ supports it using reference variables
• You cannot make the reference variable point to
another location after initialization
• See ReferenceStandalone.cpp
• See ReferencePointer.cpp
Operators in C++
• Scope Resolution (::)
– ScopeResolution.cpp
• Member Dereferencing (::*, *, ->*)
Operator Description
::* Declare a pointer to a member of a class
To access a member using object name and a pointer to
*
that member
To access a member using a pointer to the object and a
->*
pointer to that member