0% found this document useful (0 votes)
5 views24 pages

C++ Notes

The document provides an overview of user-defined data types in C++, including classes, structures, unions, enumerations, and typedefs. It explains the characteristics and syntax of each type, as well as the differences between variable declaration and definition, and types of variables based on scope. Additionally, it covers C++ features such as comments, keywords, manipulators, and the scope resolution operator.

Uploaded by

MyDream 4U
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views24 pages

C++ Notes

The document provides an overview of user-defined data types in C++, including classes, structures, unions, enumerations, and typedefs. It explains the characteristics and syntax of each type, as well as the differences between variable declaration and definition, and types of variables based on scope. Additionally, it covers C++ features such as comments, keywords, manipulators, and the scope resolution operator.

Uploaded by

MyDream 4U
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Creating new data types

User defined Data Types in C++

Data types are means to identify the type of data and associated operations of
handling it. There are three types of data types:

1. Pre-defined DataTypes
2. Derived Data Types
3. User-defined DataTypes

User-Defined DataTypes:

The data types that are defined by the user are called the derived datatype or user-
defined derived data type.
These types include:

 Class
 Structure
 Union
 Enumeration
 Typedef defined DataType

Below is the detailed description of the following types:


1. Class: The building block of C++ that leads to Object-Oriented
programming is a Class. It is a user-defined data type, which holds its own
data members and member functions, which can be accessed and used by
creating an instance of that class. A class is like a blueprint for an object.
2. Structure: A structure is a user defined data type in C/C++. A structure
creates a data type that can be used to group items of possibly different types
into a single type.

Syntax:
struct address {
char name[50];
char street[100];
char city[50];
char state[20];
int pin;
};

3. Union: Like Structures, union is a user defined data type. In union, all
members share the same memory location. For example in the following C
program, both x and y share the same location. If we change x, we can see
the changes being reflected in y.

#include <iostream>
using namespace std;

// Declaration of union is same as the structures


union test {
int x, y;
};

int main()
{
// A union variable t
union test t;

// t.y also gets value 2


t.x = 2;

cout << "After making x = 2:"


<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;

// t.x is also updated to 10


t.y = 10;

cout << "After making Y = 10:"


<< endl
<< "x = " << t.x
<< ", y = " << t.y
<< endl;

return 0;
}

4. Enumeration: Enumeration (or enum) is a user defined data type in C. It is


mainly used to assign names to integral constants, the names make a
program easy to read and maintain.
Syntax:
enum State {Working = 1, Failed = 0};
// Program to demonstrate working
// of enum in C++

#include <iostream>
using namespace std;

enum week { Mon,


Tue,
Wed,
Thur,
Fri,
Sat,
Sun };

int main()
{
enum week day;

day = Wed;
cout << day;

return 0;
}

5. Typedef : C++ allows you to define explicitly new data type names by using
the keyword typedef. Using typedef does not actually create a new data
class, rather it defines a name for an existing type. This can increase the
portability(the ability of a program to be used across different types of
machines; i.e., mini, mainframe, micro, etc; without much changes into the
code)of a program as only the typedef statements would have to be changed.
Using typedef one can also aid in self-documenting code by allowing
descriptive names for the standard data types.

Syntax:

typedef type name;

where type is any C++ data type and name is the new name for this data type.
This defines another name for the standard type of C++.

Example:

// C++ program to demonstrate typedef


#include <iostream>
using namespace std;

// After this line BYTE can be used


// in place of unsigned char
typedef unsigned char BYTE;

int main()
{
BYTE b1, b2;
b1 = 'c';
cout << " " << b1;
return 0;
}
Output:
c

C++ Features:
Ss Typedef : C++ allows you to define explicitly new data type names by using the keyword
typedef. Using typedef does not actually create a new data class, rather it defines a name for an
existing type. This can increase the portability(the ability of a program to be used across different
types of machines; i.e., mini, mainframe, micro, etc; without much changes into the code)of a
program as only the typedef statements would have to be changed. Using typedef one can also
aid in self-documenting code by allowing descriptive names for the standard data types.

Syntax:

typedef type name;

where type is any C++ data type and name is the new name for this data type.
This defines another name for the standard type of C++.

Example:

// C++ program to demonstrate typedef


#include <iostream>
using namespace std;

// After this line BYTE can be used


// in place of unsigned char
typedef unsigned char BYTE;

int main()
{
BYTE b1, b2;
b1 = 'c';
cout << " " << b1;
return 0;
}
Output:
c
Basic Input / Output in C++

iostream.h header files


C++ comes with libraries that provide us with many ways for performing input and output. In C++ input
and output are performed in the form of a sequence of bytes or more commonly known as streams.

 Input Stream: If the direction of flow of bytes is from the device(for example,
Keyboard) to the main memory then this process is called input.
 Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to
device( display screen ) then this process is called output.

C++ Comments
Comments can be used to explain C++ code, and to make it more
readable. It can also be used to prevent execution when testing
alternative code. Comments can be singled-lined or multi-lined.
Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will not be executed).

This example uses a single-line comment before a line of code:

Example
// This is a comment
cout << "Hello World!";

This example uses a single-line comment at the end of a line of code:

Example
cout << "Hello World!"; // This is a comment
C++ Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Example
/* The code below will print the words Hello World!
to the screen, and it is amazing */
cout << "Hello World!";

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

Variables in C++

A variable is a name given to a memory location. It is the basic unit of storage in a program.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
 In C++, all the variables must be declared before use.
 How to declare variables?
 A typical variable declaration is of the form:

 // Declaring a single variable


 type variable_name;

 // Declaring multiple variables:
 type variable1_name, variable2_name, variable3_name;
 A variable name can consist of alphabets (both upper and lower case), numbers and the
underscore ‘_’ character. However, the name must not start with a number.


In the above diagram,

datatype: Type of data that can be stored in this variable.


variable_name: Name given to the variable.
value: It is the initial value stored in the variable.

Examples:

// Declaring float variable


float simpleInterest;

// Declaring integer variable


int time, speed;

// Declaring character variable


char var;

Difference between variable declaration and definition

The variable declaration refers to the part where a variable is first declared or introduced before
its first use. A variable definition is a part where the variable is assigned a memory location and
a value. Most of the times, variable declaration and definition are done together.
See the following C++ program for better clarification:

#include <iostream>
using namespace std;

int main()
{
// declaration and definition
// of variable 'a123'
char a123 = 'a';

// This is also both declaration and definition


// as 'b' is allocated memory and
// assigned some garbage value.
float b;

// multiple declarations and definitions


int _c, _d45, e;

// Let us print a variable


cout << a123 << endl;

return 0;
}
Output:
a

Types of variables

There are three types of variables based on the scope of variables in C++:

 Local Variables
 Instance Variables
 Static Variables

Let us now learn about each one of these variables in detail.

1. Local Variables: A variable defined within a block or method or constructor is called


local variable.
o These variable are created when the block in entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
o The scope of these variables exists only within the block in which the variable is
declared. i.e. we can access these variable only within that block.
o Initialisation of Local Variable is Mandatory.

2. Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor or block.
o As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
o Unlike local variables, we may use access specifiers for instance variables. If we
do not specify any access specifier then the default access specifier will be used.
o Initialisation of Instance Variable is not Mandatory.
o Instance Variable can be accessed only by creating objects.

3. Static Variables: Static variables are also known as Class variables.


o These variables are declared similarly as instance variables, the difference is that
static variables are declared using the static keyword within a class outside any
method constructor or block.
o Unlike instance variables, we can only have one copy of a static variable per class
irrespective of how many objects we create.
o Static variables are created at the start of program execution and destroyed
automatically when execution ends.
o Initialization of Static Variable is not Mandatory. Its default value is 0
o If we access the static variable like Instance variable (through an object), the
compiler will show the warning message and it won’t halt the program. The
compiler will replace the object name to class name automatically.
o If we access the static variable without the class name, Compiler will
automatically append the class name.

Instance variable Vs Static variable

 Each object will have its own copy of instance variable whereas We can only have one
copy of a static variable per class irrespective of how many objects we create.
 Changes made in an instance variable using one object will not be reflected in other
objects as each object has its own copy of instance variable. In case of static, changes will
be reflected in other objects as static variables are common to all object of a class.
 We can access instance variables through object references and Static Variables can be
accessed directly using class name.

Syntax for static and instance variables:

class Example
{
static int a; // static variable
int b; // instance variable
}

Const Qualifier in C
We use the const qualifier to declare a variable as constant. That means that we cannot change
the value once the variable has been initialized. Using const has a very big benefit. For example,
if you have a constant value of the value of PI, you wouldn't like any part of the program to
modify that value. So you should declare that as a const.

Objects declared with const-qualified types may be placed in read-only memory by the compiler,
and if the address of a const object is never taken in a program, it may not be stored at all. For
example,

#include<iostream>
using namespace std;
int main() {
const int x = 10;
x = 12;
return 0;
}

This program would produce an error as we have tried to reassign a const value.

Manipulators in C++
Manipulators are helping functions that can modify the input/output stream. It does not mean
that we change the value of a variable, it only modifies the I/O stream using insertion (<<) and
extraction (>>) operators.

C++ Manipulator endl


C++ manipulator endl function is used to insert a new line character and flush the stream.
Working of endl manipulator is similar to '\n' character in C++. It prints the output of the
following statement in the next line.

Syntax

for ostream

ostream& endl (ostream& os);

basic template

template <class charT, class traits>

basic_ostream<charT,traits>& endl (basic_ostream<charT,traits>& os);

Parameter

os: Output stream object affected.

Return value

It returns argument os.

Setw Manipulator
setw C++ is a method of iomaip library present in C++. setw function is a C++ manipulator
which stands for set width. The manipulator sets the ios library field width or specifies the
minimum number of character positions a variable will consume. In simple terms, the setw C++
function helps set the field width used for output operations. The function takes member width as
an argument and needs a stream where this field has to be manipulated or inserted. The function
also sets the width parameter of the stream in or stream out exactly n times. The parameter it
takes will be the new value that needs to be set as the width

Syntax of setw C++

The syntax of the function is:

Cout<<setw(number);

cout << std::setw(5);


setprecision() Manipulator
C++ manipulator setprecision function is used to control the number of digits of an output
stream display of a floating- point value.

This manipulator is declared in header file <iomanip>.

Syntax

setprecision (int n);

Parameter

n: new value for the decimal precision.

Return value

This function returns an object of unspecified type. The setbase function should only be used as a
stream manipulator.

Scope resolution operator in C++


In C++, scope resolution operator is ::. It is used for following purposes.

1) To access a global variable when there is a local variable with


same name:
// C++ program to show that we can access a global variable
// using scope resolution operator :: when there is a local
// variable with same name
#include<iostream>
using namespace std;

int x; // Global x

int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
Output:

Value of global x is 0
Value of local x is 10

2) To define a function outside a class.


// C++ program to show that scope resolution operator :: is used
// to define a function outside a class
#include<iostream>
using namespace std;

class A
{
public:

// Only declaration
void fun();
};

// Definition outside class using ::


void A::fun()
{
cout << "fun() called";
}

int main()
{
A a;
[Link]();
return 0;
}

Output:

fun() called

3) To access a class’s static variables.


// C++ program to show that :: can be used to access static
// members when there is a local variable with same name
#include<iostream>
using namespace std;

class Test
{
static int x;
public:
static int y;
// Local parameter 'a' hides class member
// 'a', but we can access it using ::
void func(int x)
{
// We can access class's static variable
// even if there is a local variable
cout << "Value of static x is " << Test::x;

cout << "\nValue of local x is " << x;


}
};

// In C++, static members must be explicitly defined


// like this
int Test::x = 1;
int Test::y = 2;

int main()
{
Test obj;
int x = 3 ;
[Link](x);

cout << "\nTest::y = " << Test::y;

return 0;
}

Output:

Value of static x is 1
Value of local x is 3
Test::y = 2;

4) In case of multiple Inheritance:


If same variable name exists in two ancestor classes, we can use scope resolution operator to
distinguish.

// Use of scope resolution operator in multiple inheritance.


#include<iostream>
using namespace std;

class A
{
protected:
int x;
public:
A() { x = 10; }
};
class B
{
protected:
int x;
public:
B() { x = 20; }
};

class C: public A, public B


{
public:
void fun()
{
cout << "A's x is " << A::x;
cout << "\nB's x is " << B::x;
}
};

int main()
{
C c;
[Link]();
return 0;
}

Output:

A's x is 10
B's x is 20

5) For namespace
If a class having the same name exists inside two namespace we can use the namespace name
with the scope resolution operator to refer that class without any conflicts

// Use of scope resolution operator for namespace.


#include<iostream>

int main(){
std::cout << "Hello" << std::endl;

}
Here, cout and endl belong to the std namespace.

6) Refer to a class inside another class:


If a class exists inside another class we can use the nesting class to refer the nested class using
the scope resolution operator

// Use of scope resolution class inside another class.


#include<iostream>
using namespace std;
class outside
{
public:
int x;
class inside
{
public:
int x;
static int y;
int foo();

};
};
int outside::inside::y = 5;

int main(){
outside A;
outside::inside B;

Please write comments if you find anything incorrect, or you want to share more information
about the topic discussed above

new and delete Operators in C++ For


Dynamic Memory
Dynamic memory allocation in C/C++ refers to performing memory allocation manually by a
programmer. Dynamically allocated memory is allocated on Heap and non-static and local
variables get memory allocated on Stack (Refer to Memory Layout C Programs for details).

What are applications?

 One use of dynamically allocated memory is to allocate memory of variable size which is not
possible with compiler allocated memory except for variable-length arrays.
 The most important use is the flexibility provided to programmers. We are free to allocate and
deallocate memory whenever we need it and whenever we don’t need it anymore. There are
many cases where this flexibility helps. Examples of such cases are Linked List, Tree, etc.

How is it different from memory allocated to normal variables?

For normal variables like “int a”, “char str[10]”, etc, memory is automatically allocated and
deallocated. For dynamically allocated memory like “int *p = new int[10]”, it is the
programmer’s responsibility to deallocate memory when no longer needed. If the programmer
doesn’t deallocate memory, it causes a memory leak (memory is not deallocated until the
program terminates).

How is memory allocated/deallocated in C++?

C uses the malloc() and calloc() function to allocate memory dynamically at run time and uses a
free() function to free dynamically allocated memory. C++ supports these functions and also has
two operators new and delete that perform the task of allocating and freeing the memory in a
better and easier way.

new operator

The new operator denotes a request for memory allocation on the Free Store. If sufficient
memory is available, a new operator initializes the memory and returns the address of the newly
allocated and initialized memory to the pointer variable.

Syntax to use new operator

pointer-variable = new data-type;

Here, pointer-variable is the pointer of type data-type. Data-type could be any built-in data type
including array or any user-defined data type including structure and class.

Example:

// Pointer initialized with NULL


// Then request memory for the variable
int *p = NULL;
p = new int;

OR

// Combine declaration of pointer


// and their assignment
int *p = new int;

Initialize memory: We can also initialize the memory for built-in data types using a new
operator. For custom data types a constructor is required (with the data type as input) for
initializing the value. Here’s an example of the initialization of both data types :

pointer-variable = new data-type(value);

Example:

int *p = new int(25);


float *q = new float(75.25);
// Custom data type
struct cust
{
int p;
cust(int q) : p(q) {}
};

// Works fine, doesn’t require constructor


cust* var1 = new cust;

OR

// Works fine, doesn’t require constructor


cust* var1 = new cust();

// Notice error if you comment this line


cust* var = new cust(25)

Allocate a block of memory: new operator is also used to allocate a block(an array) of memory
of type data-type.

pointer-variable = new data-type[size];

where size(a variable) specifies the number of elements in an array.

Example:

int *p = new int[10]

Dynamically allocates memory for 10 integers continuously of type int and returns a pointer to
the first element of the sequence, which is assigned top(a pointer). p[0] refers to the first element,
p[1] refers to the second element, and so on.

Normal Array Declaration vs Using new

There is a difference between declaring a normal array and allocating a block of memory using
new. The most important difference is, that normal arrays are deallocated by the compiler (If the
array is local, then deallocated when the function returns or completes). However, dynamically
allocated arrays always remain there until either they are deallocated by the programmer or the
program terminates.

What if enough memory is not available during runtime?

If enough memory is not available in the heap to allocate, the new request indicates failure by
throwing an exception of type std::bad_alloc, unless “nothrow” is used with the new operator, in
which case it returns a NULL pointer (scroll to section “Exception handling of new operator” in
this article). Therefore, it may be a good idea to check for the pointer variable produced by the
new before using its program.

int *p = new(nothrow) int;


if (!p)
{
cout << "Memory allocation failed\n";
}

delete operator

Since it is the programmer’s responsibility to deallocate dynamically allocated memory,


programmers are provided delete operator in C++ language.

Syntax:

// Release memory pointed by pointer-variable


delete pointer-variable;

Here, pointer-variable is the pointer that points to the data object created by new.

Examples:

delete p;
delete q;

To free the dynamically allocated array pointed by pointer-variable, use the following form of
delete:

// Release block of memory


// pointed by pointer-variable
delete[] pointer-variable;

Example:

// It will free the entire array


// pointed by p.
delete[] p;
// C++ program to illustrate dynamic allocation

// and deallocation of memory using new and delete


#include <iostream>

using namespace std;

int main ()

// Pointer initialization to null

int* p = NULL;

// Request memory for the variable

// using new operator

p = new(nothrow) int;

if (!p)

cout << "allocation of memory failed\n";

else

// Store value at allocated address

*p = 29;

cout << "Value of p: " << *p << endl;

// Request block of memory

// using new operator

float *r = new float(75.25);

cout << "Value of r: " << *r << endl;

// Request block of memory of size n


int n = 5;

int *q = new(nothrow) int[n];

if (!q)

cout << "allocation of memory failed\n";

else

for (int i = 0; i < n; i++)

q[i] = i+1;

cout << "Value store in block of memory: ";

for (int i = 0; i < n; i++)

cout << q[i] << " ";

// freed the allocated memory

delete p;

delete r;

// freed the block of allocated memory

delete[] q;

return 0;

Output:

Value of p: 29
Value of r: 75.25
Value store in block of memory: 1 2 3 4 5

You might also like