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

Operators in C++

C++ sizeof Operator


The sizeof operator is a unary compile-time operator used to determine the size of variables, data
types, and constants in bytes at compile time. It can also determine the size of classes, structures, and
unions.

Scope resolution operator in C++


1. To access a global variable when there is a local variable with same name.
2. To define a function outside a class.
3. To access a class’s static variables.
4. In case of multiple Inheritance: If the 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;
c.fun();
return 0;
}

5. For namespace
6. Refer to a class inside another class
7. Refer to a member of the base class in the derived object
// Refer to a member of the base class in the derived object.
#include <iostream>

class Base {
public:
void func()
{
std::cout << "This is Base class" << std::endl;
}
};

class Derived : public Base {


public:
void func()
{
std::cout << "This is Derived class" << std::endl;
}
};

int main()
{
Derived obj;
obj.Base::func();
obj.func();
return 0;
}

std::endl vs \n in C++
std::cout << std::endl inserts a new line and flushes the stream(output buffer), whereas
std::cout << “\n” just inserts a new line.Therefore, std::cout << std::endl; can be said
equivalent to std::cout << ‘\n’ << flush;

endl \n

It is a manipulator. It is a character.

It doesn’t occupy any memory. It occupies 1 byte memory as it is a character.

It is a keyword and would not specify any It can be stored in a string and will still convey
meaning when stored in a string. its specific meaning of line break.
endl \n

It is only supported by C++. It is supported in both C and C++.

Basic Input / Output in C++


Standard output stream (cout): Usually the standard output device is the display screen. The
C++ cout statement is the instance of the ostream class. It is used to produce output on the
standard output device which is usually the display screen. The data needed to be displayed on
the screen is inserted in the standard output stream (cout) using the insertion operator(<<).
Standard input stream (cin): Usually the input device in a computer is the keyboard. C++ cin
statement is the instance of the class istream and is used to read input from the standard input
device which is usually a keyboard.
The extraction operator(>>) is used along with the object cin for reading inputs. The extraction
operator extracts the data from the object cin which is entered using the keyboard.

You might also like