0% found this document useful (0 votes)
3 views

BasicsOfCPP

C++ is an object-oriented programming language that combines features from Simula67 and C, introducing concepts such as classes, inheritance, and operator overloading for better program structure and maintenance. It utilizes commands like g++ for compilation and includes predefined objects like cout and cin for output and input operations. The document also covers various data types, user-defined types, memory management, functions, and operator overloading, providing a comprehensive overview of C++ programming fundamentals.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

BasicsOfCPP

C++ is an object-oriented programming language that combines features from Simula67 and C, introducing concepts such as classes, inheritance, and operator overloading for better program structure and maintenance. It utilizes commands like g++ for compilation and includes predefined objects like cout and cin for output and input operations. The document also covers various data types, user-defined types, memory management, functions, and operator overloading, providing a comprehensive overview of C++ programming fundamentals.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Basics of C++

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

• Memory Management (new and delete)


new operator
• Like malloc and calloc in C
• Allocates memory in free store, hence called free
store operator
• data-type * ptr-variable = new data-type;
• data-type * ptr-variable = new data-type(value);
• E.g. int * p = new int;
• OR int * p = new int(10);
• Can be used with arrays, classes and structures
• E.g. int * arr = new int[10];
• OR int * arr = new int[m][3][2];
• Array size is mandatory
new and delete operator
• Usage with class: class Student { … }
• Student * s = new Student;
• In case memory is not available for allocation, new
will return null or throw exception depending on
compiler. So recommended to check for null or
handle exception
• Memory allocated using new can be released using
delete operator
• Syntax: delete ptr-variable;
• E.g. delete p; (int * p = new int;)
• See MemoryAllocation.cpp,
MemoryAllocationObject.cpp
new vs malloc
• It automatically computes the size of the data
object. We need not use the operator sizeof.
• It automatically returns the correct pointer type, so
that there is no need to use a type cast.
• It is possible to initialize the object while creating
the memory space.
• Like any other operator, new and delete can be
overloaded.
Typecasting
• Explicit type conversion
• Syntax:
– (data-type) expression // C syntax
– data-type (expression) // C++ syntax
– p = (int) q // Valid
– p = int (q) // Valid
– p = (int *) q // Valid
– p = int * (q) // Invalid
• typedef int * int_ptr;
• p = int_ptr (q) // Valid
Implicit Conversions
• Automatic conversion of smaller type to wider type
Implicit Conversions
Expressions and their types
• Constant e.g. 20 + 5 / 2.0, ‘a’
• Integral e.g. m * n – 5, 5 + int(2.0)
• Float e.g. x + y / 2, 10.5, 5 + float(2)
• Pointer e.g. &m, ptr + 1, “abc”
• Relational (Boolean) e.g. x <= y, m+n == o+p
• Logical e.g. m>n && o==10, m==1 || n==2
• Bitwise e.g. x << 3, y >> 1
• In above examples:
– m, n, o and p are integers
– x and y are floats
– ptr is a pointer variable
Special Assignment Expressions
• Chained
– x = y = 10 OR x = (y = 10)
• Embedded
– x = (y = 10) + 20 OR y = 10; x = y + 20;
• Compound
– x = x + 10 OR x += 10
Operator Overloading
• Assign different meanings to an operation
• E.g. * is used for multiplication and declaring
pointers
• << and >> are used for shifting bits as well as IO
• All operators except below can be overloaded
– Member-access . and .*
– Conditional ?:
– Scope resolution ::
– Size operator sizeof
Operator Precedence
Control Structures
• If Conditional / Branching
• Switch Conditional / Branching
• do-while Loop / Iteration / Repetition
• while Loop / Iteration / Repetition
• for Loop / Iteration / Repetition
Functions
• Same as C
• main function has return type int
– Should have a return statement at the end
– 0 means successful, non-zero indicates error
• Function prototyping
– return-type function-name(argument-list);
– E.g. float volume(int x, int y, int z);
– OR float volume(int, int, int); // Declaration is valid
– Variable names for arguments are compulsory in
function definition
Function call and return by reference
• Normal function calls are call by value
– Values passed are copied to another set of variables
defined locally in the function
• If you want to alter the values of variables in the
calling functions, functions should be called by
reference
• See ReferencePointer.cpp
• Function can return a reference instead of variable
• This allows functions to be on LHS of assignment
• See ReferenceReturn.cpp
Inline functions
• Normal function calls include overhead of
transferring control to another function and getting
it back after execution
• For small functions, recommended to use macros or
inline functions as during compilation function code
replaces the function calls
• Macros don’t have error checking during
compilation
• Hence inline functions are better than macros for
readability
• Syntax: inline ret-type fn-name(arg-list) {…}
• E.g. inline float cubevolume(float a) {…}
Inline functions
• Inline keyword sends request, not command, to the
compiler
• So compiler might ignore
• Situations where inline expansion might not work
– For functions returning values having if, switch, loops,
goto
– Functions not returning values, having return statement
– Functions having static variables
– Recursive functions
• See InlineFunction.cpp
Default Arguments
• Functions can have default values for trailing
arguments
• If value is not provided for argument with default
value, the default value is used during execution
• See DefaultArguments.cpp
• Benefits
– More parameters with default values can be added to
existing functions without breaking existing code
– Combine similar functions into one. e.g. addition of 2
numbers or 3 numbers can be achieved using 1 function
const Arguments
• Argument to a function can be declared constant.
Function cannot change the value of the variable
• E.g. int strlen(const char *p)
• See ConstArguments.cpp
Recursion
• Function calling itself
• Should have if for exiting infinite loop
• See Recursion.cpp
Function Overloading
• Use same function name for different tasks
• Multiple functions with same name and different
arguments can be created for different tasks
• Function selection involves below steps
1. Find exact match of argument types, number and order
2. Implicit (Built-in) conversions to actual arguments
• Multiple matches i.e. int to long as well as double, gives error
• E.g. f(10) call gives error when f(long) and f(double) both exist
3. User defined conversions in combination with integral
and implicit conversions
• See FunctionOverloading.cpp
Math Library Functions
• Include cmath
Function name Description
ceil(x) Rounds to smallest integer not less than x
cos(x) Trigonometric cosine
exp(x) Ex
fabs(x) Absolute value of x, always 0 or positive
floor(x) Rounds to largest integer not greater than x
log(x) Natural log (Base e)
log10(x) Log (Base 10)
pow(x,y) x raised to the power of y
sin(x) Trigonometric sine
sqrt(x) Square root
tan(x) Trigonometric tangent

You might also like