A C++ (cpp) repository about the unknown, lesser known, and the most important facts and concepts.
🟥🟩🟦
🟥🟩🟦
🟥🟩🟦
Programmer writes the source code in plain text, often in an IDE (Integrated Development Environment). The program is then compiled (converted) to a language that the computer can understand, and run as a program. This is normally a two step process that consists of: 1. Pulling in any specified header files and creating Assembly (or object) code native to the processor. 2. Using a linker program to pull in any other object or library files required, to finally output machine code (1's and 0's). This resulting code is usually known as a binary or executable file. The program can then be run (or executed) on the computer.
🟥🟩🟦
Buffer-: A region of storage used to hold data. IO facilities often store input or output in a buffer and read or write the buffer independently from actions in the program. Using a buffer allows the operating system to combine several output operations from our program into a single system-level write. Output buffers can be explicitly flushed to force the buffer to be written. By default, reading cin flushes cout; cout is also flushed when the program ends normally. By default, All output buffers are flushed as part of the return from main.
Note-: cout is an object of ostream class and cin is an object of istream class.
Manipulator-: Object, such as std::endl, that when read or written “manipulates” the stream itself. Clearing output buffer-:
e.g. If three cout statements prints 1,2,3 respectively, without any cin statement in between or any manipulator used would print the three numbers on the same line but using endl will write the output of each cout statement on a seperate new line.
Disadvantage-: Flushing of buffers is an Operating System task. Each time the buffer is flushed, a request has to be made to the OS and these requests are comparatively expensive. Furthermore, we don’t really need to flush the buffer every time we write something to the stream, since the buffers get flushed automatically when they get full. Solution-: Writing ‘\n’ characters directly to the stream is more efficient since it doesn’t force a flush like std::endl.
Clearing input buffer-: In case of C++, after encountering“cin” statement, we require to input a character array or a string , we require to clear the input buffer or else the desired input is occupied by buffer of previous variable, not by the desired container. Solution-: Typing “cin>>ws” after “cin” statement tells the compiler to ignore buffer and also to discard all the whitespaces before the actual content of string or character array.
🟥🟩🟦
A typical memory representation of C++ program consists of following sections.
#include <stdio.h>
void firstFunc() ;
void secondFunc() ;
int main() {
firstFunc() ;
return 0 ;
}
void firstFunc() {
int myInt = 17 ;
secondFunc() ;
}
void secondFunc() {
int yourInt = 42 ;
char myChar = 'd' ;
}
Q-N-A -:
🟥🟩🟦
They are signals generated when serious program error is detected by the operating system and there is no way the program could continue to execute because of these errors.
🟥🟩🟦
#include <bits/stdc++.h>
using namespace std;
int countWords(string str)
{
// breaking input into word using string stream
stringstream s(str); // Used for breaking words
string word; // to store individual words
int count = 0;
while (s >> word)
count++;
return count;
}
int main()
{
string s = "geeks for geeks geeks "
"contribution placements";
cout << " Number of words are: " << countWords(s);
return 0;
}
Storage for Strings in C++
Note-: When a string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read-only block (generally in data segment) that is shared among functions.
e.g. char *str= = "GfG";
In the above line “GfG” is stored in a shared read-only location, but pointer str is stored in a read-write memory. You can change str to point something else but cannot change value at the address present at str i.e. str="mno" is possible but *str="nmo" is not. The former is a Segmentation Fault. (For more info jump to Faults section).
🟥🟩🟦
#include<iostream>
using namespace std;
// Passing array by value
void aDecay(int *p)
{ cout << "Modified size of array is by "
" passing by value: ";
cout << sizeof(p) << endl;
cout << *p << endl;
cout << *(++p) << endl;
}
// Function to show that array decay happens
// even if we use pointer
void pDecay(int (*p)[7])
{ cout << "Modified size of array by "
"passing by pointer: ";
cout << sizeof(p) << endl;
cout << *p << endl;
cout << *(++p )<< endl;
}
int main()
{
int a[7] = {1, 2, 3, 4, 5, 6, 7,};
cout << "Actual size of array is: ";
cout << sizeof(a) <<endl;
aDecay(a);
pDecay(&a);
return 0;
}
Actual size of array is: 28
Modified size of array is by passing by value: 8
1
2
Modified size of array by passing by pointer: 8
0x7fff168bcab0
0x7fff168bcacc
🟥🟩🟦
class Node {
private:
int key;
Node* next;
// Other members of Node Class
friend int LinkedList::search();
// Only search() of linkedList
// can access internal members
};
🟥🟩🟦
Types of pointers-:
#include<stdlib.h>
int main()
{
int x = 4;
float y = 5.5;
void * ptr;
ptr = &x;
// (int*)ptr - does type casting of void
// *((int*)ptr) dereferences the typecasted
printf("Integer variable is = %d", *( (int*) ptr) );
ptr = &y;
printf("\nFloat variable is= %f", *( (float*) ptr) );
return 0;
}
#include<iostream>
using namespace std;
class Test
{
int x;
public:
void setX (int x)
{ // The 'this' pointer is used to retrieve the object's x
// hidden by the local variable 'x'
this->x = x;
}
void print() { cout << "x = " << x << endl; }
};
int main()
{
Test obj;
int x = 20;
obj.setX(x);
obj.print();
return 0;
}
#include<iostream>
using namespace std;
class Test
{
int x;
int y;
public:
Test(int x = 0, int y = 0) { this->x = x; this->y = y; }
Test &setX(int a) { x = a; return *this; }
Test &setY(int b) { y = b; return *this; }
void print() { cout << "x = " << x << " y = " << y << endl; }
};
int main()
{
Test obj1(5, 5);
obj1.setX(10).setY(20);
obj1.print();
return 0;
}
🟥🟩🟦
class Node {
private:
int key;
Node* next;
// Other members of Node Class
// Now class LinkedList can
// access private members of Node
friend class LinkedList;
};
**Compiler's Optimizations**
1. Copy Elision-: or Copy omission is a compiler optimization technique that avoids unnecessary copying of objects.
e.g. For B ob = "copy me"; // B is a class
According to theory, when the object “ob” is being constructed, one argument constructor is used to convert “copy me” to a temporary object & that
temporary object is copied to the object “ob”. But now the call to the copy constructor is elided.
2. Return Value Optimization-: is a compiler optimization that involves eliminating the temporary object created to hold a function's return value.
#include<iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
Point(int x1, int y1) { x = x1; y = y1; }
Point(const Point& p1) {x = p1.x; y = p1.y; }
int getX() { return x; }
int getY() { return y; }
};
int main()
{
Point p1(10, 15); // Normal constructor is called here
Point p2=p1; // Copy constructor is called here
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY();
return 0;
}
A copy constructor is called when an object is passed by value. Copy constructor itself is a function. So if we pass an argument by value in a copy
constructor, a call to copy constructor would be made to call copy constructor which becomes a non-terminating chain of calls. Therefore compiler doesn’t
allow parameters to be passed by value.
Why const?
#include<iostream>
using namespace std;
class Test
{
/* Class data members */
public:
Test(Test &t) { /* Copy data members from t*/}
Test() { /* Initialize data members */ }
};
Test fun()
{
cout << "fun() Called\n";
Test t;
return t;
}
int main()
{
Test t1;
Test t2 = fun();
return 0;
}
>>>Compile time error. Reason-: The function fun() returns by value. So the compiler creates a temporary object which is copied to t2 using copy constructor
in the original program (The temporary object is passed as an argument to copy constructor). The reason for compiler error is, compiler created temporary
objects cannot be bound to non-const references because it doesn’t make sense to modify compiler created temporary objects as they can die any moment.
Solution-: 1. Use const. 2. Test t2; t2 = fun();
In C++, a Copy Constructor may be called in following cases:
1. When an object of the class is returned by value.
2. When an object of the class is passed (to a function) by value as an argument.
3. When an object is constructed based on another object of the same class.
4. When the compiler generates a temporary object.
It is, however, not guaranteed that a copy constructor will be called in all these cases, because the C++ Standard allows the compiler to optimize the copy
away in certain cases, one example is the return value optimization (sometimes referred to as RVO)
Note-: In C++ computer programming, copy elision refers to a compiler optimization technique that eliminates unnecessary copying of objects. The C++
language standard generally allows implementations to perform any optimization, provided the resulting program's observable behavior is the same as if, i.e.
pretending, the program were executed exactly as mandated by the standard.
In the context of the C++ programming language, return value optimization (RVO) is a compiler optimization that involves eliminating the temporary object
created to hold a function's return value.The standard also describes a few situations where copying can be eliminated even if this would alter the
program's behavior, the most common being the return value optimization.
If we don’t define our own copy constructor, the C++ compiler creates a default copy constructor for each class which does a member-wise copy between
objects. The compiler created copy constructor works fine in general. We need to define our own copy constructor only if an object has pointers or any
runtime allocation of the resource like file handle, a network connection..etc. Default copy constructor does only shallow copy. Deep copy is possible only
with user defined copy constructor.
Copy constructor is called when a new object is created from an existing object, as a copy of the existing object (see this G-Fact). And assignment operator
is called when an already initialized object is assigned a new value from another existing object.
🟥🟩🟦
int count_calls()
{
static int ctr = 0; // value will persist across calls
return ++ctr;
}
int main()
{
for (int i = 0; i != 10; ++i)
cout << count_calls() << endl;
return 0;
}
class Account {
public:
void calculate() { amount += amount * interestRate; }
static double rate() { return interestRate; }
static void rate(double);
private:
std::string owner;
double amount;
static double interestRate;
static double initRate();
};
void Account::rate(double newRate)
{
interestRate = newRate;
}
int main(){
double r;
r = Account::rate();
Account ac1;
Account * ac2 = &ac1;
r = ac1.rate();
r = ac2->rate();
#include<iostream>
using namespace std;
class GfG
{
int i = 0;
public:
GfG()
{
i = 0;
cout << "Inside Constructor\n";
}
~GfG()
{
cout << "Inside Destructor\n";
}
};
int main()
{
int x = 0;
if (x==0)
{
static GfG obj;
}
cout << "End of main\n";
}
🟥🟩🟦
Types-:
🟥🟩🟦
#include<iostream>
using namespace std;
class Base
{ int x;
public:
Base(int i)
{ x = i;
cout << "Base Parameterized Constructor\n";
}
};
class Derived : public Base
{ int y;
public:
// parameterized constructor
Derived(int j):Base(j)
{ y = j;
cout << "Derived Parameterized Constructor\n";
}
};
int main()
{ Derived d(10) ;
}
🟥🟩🟦
#include <iostream>
using namespace std;
class Person
{
//content of Person
};
class Employee:public Person
{
public:
Employee(string fName, string lName, double sal)
{
FirstName = fName;
LastName = lName;
salary = sal;
}
string FirstName;
string LastName;
double salary;
void show()
{
cout << "First Name: " << FirstName << " Last Name: " << LastName << " Salary: " << salary<< endl;
}
void addBonus(double bonus)
{
salary += bonus;
}
};
class Manager :public Employee
{
public:
Manager(string fName, string lName, double sal, double comm) :Employee(fName, lName, sal)
{
Commision = comm;
}
double Commision;
double getComm()
{
return Commision;
}
};
class Clerk :public Employee
{
public:
Clerk(string fName, string lName, double sal, Manager* man) :Employee(fName, lName, sal)
{
manager = man;
}
Manager* manager;
Manager* getManager()
{
return manager;
}
};
void congratulate(Employee* emp) //generic function
{
cout << "Happy Birthday!!!" << endl;
emp->addBonus(200);
emp->show();
};
int main()
{
//pointer to base class object
Employee* emp;
//object of derived class
Manager m1("Steve", "Kent", 3000, 0.2);
Clerk c1("Kevin","Jones", 1000, &m1);
//implicit upcasting
emp = &m1;
//It's ok
cout<<emp->FirstName<<endl;
cout<<emp->salary<<endl;
//Fails because upcasting is used
//cout<<emp->getComm();
congratulate(&c1);
congratulate(&m1);
cout<<"Manager of "<<c1.FirstName<<" is "<<c1.getManager()->FirstName;
}
>>Steve
3000
Happy Birthday!!!
First Name: Kevin Last Name: Jones Salary: 1200
Happy Birthday!!!
First Name: Steve Last Name: Kent Salary: 3200
Manager of Kevin is Steve
//pointer to base class object
Employee* emp;
//object of derived class
Manager m1("Steve", "Kent", 3000, 0.2);
//implicit upcasting
emp = &m1;
//explicit downcasting from Employee to Manager
Manager* m2 = (Manager*)(emp);
>>>This code compiles and runs without any problem because emp points to an object of Manager class.
But,
Employee e1("Peter", "Green", 1400);
//try to cast an employee to Manager
Manager* m3 = (Manager*)(&e1);
cout << m3->getComm() << endl;
>>>e1 object is not an object of the Manager class. It does not contain any information about the commission. That’s why such an operation can produce
unexpected results.
Employee e1("Peter", "Green", 1400);
Manager* m3 = dynamic_cast<Manager*>(&e1);
if (m3)
cout << m3->getComm() << endl;
else
cout << "Can't cast from Employee to Manager" << endl;
🟥🟩🟦
void operator<<(ostream &os, const book &item)
{
os << item.isbn() << " " << item.units_sold << " "
<< item.revenue << " " << item.avg_price();
}
Note-: Differentiating Prefix and Postfix Operators-: Normal overloading cannot distinguish between these operators. The prefix and postfix versions use the same symbol, meaning that the overloaded versions of these operators have the same name. They also have the same number and type of operands. To solve this problem, the postfix versions take an extra (unused) parameter of type int. When we use a postfix operator, the compiler supplies 0 as the argument for this parameter.
🟥🟩🟦
#include <iostream>
using namespace std;
class Base
{
protected:
int i;
public:
Base(int a) { i = a; }
virtual void display()
{ cout << "I am Base class object, i = " << i << endl; }
};
class Derived : public Base
{
int j;
public:
Derived(int a, int b) : Base(a) { j = b; }
virtual void display()
{ cout << "I am Derived class object, i = "
<< i << ", j = " << j << endl; }
};
void somefunc (Base obj)
{
obj.display();
}
int main()
{
Base b(33);
Derived d(45, 54);
somefunc(b);
somefunc(d); // Object Slicing, the member j of d is sliced off
return 0;
}
#include <iostream>
using namespace std;
class Account {
public:
Account( double d ) { _balance = d; }
virtual double GetBalance() { return _balance; }
virtual void PrintBalance() { cerr << "Error. Balance not available for base type." << endl; }
private:
double _balance;
};
class CheckingAccount : public Account {
public:
CheckingAccount(double d) : Account(d) {}
void PrintBalance() { cout << "Checking account balance: " << GetBalance() << endl; }
};
class SavingsAccount : public Account {
public:
SavingsAccount(double d) : Account(d) {}
void PrintBalance() { cout << "Savings account balance: " << GetBalance(); }
};
int main() {
CheckingAccount checking( 100.00 );
SavingsAccount savings( 1000.00 );
Account *pAccount = &checking;
pAccount->PrintBalance();
pAccount = &savings;
pAccount->PrintBalance();
}
class Employee {
public:
virtual void raiseSalary()
{
/* common raise salary code */
}
virtual void promote() { /* common promote code */ }
};
class Manager : public Employee {
virtual void raiseSalary()
{
/* Manager specific raise salary code, may contain
increment of manager specific incentives*/
}
virtual void promote()
{
/* Manager specific promote */
}
};
// Similarly, there may be other types of employees
// We need a very simple function
// to increment the salary of all employees
// Note that emp[] is an array of pointers
// and actual pointed objects can
// be any type of employees.
// This function should ideally
// be in a class like Organization,
// we have made it global to keep things simple
void globalRaiseSalary(Employee* emp[], int n)
{
for (int i = 0; i < n; i++
// Polymorphic Call: Calls raiseSalary()
// according to the actual object, not
// according to the type of pointer
emp[i]->raiseSalary();
}
#include <iostream>
using namespace std;
class A
{
public:
virtual void fun();
};
class B
{
public:
void fun();
};
int main()
{
int a = sizeof(A), b = sizeof(B);
if (a == b) cout << "a == b";
else if (a > b) cout << "a > b";
else cout << "a < b";
return 0;
}
// An abstract class
class Test
{
// Data members of class
public:
// Pure Virtual Function
virtual void show() = 0;
};
#include<iostream>
using namespace std;
class Person {
// Data members of person
public:
Person(int x) { cout << "Person::Person(int ) called" << endl; }
};
class Faculty : public Person {
// data members of Faculty
public:
Faculty(int x):Person(x) {
cout<<"Faculty::Faculty(int ) called"<< endl;
}
};
class Student : public Person {
// data members of Student
public:
Student(int x):Person(x) {
cout<<"Student::Student(int ) called"<< endl;
}
};
class TA : public Faculty, public Student {
public:
TA(int x):Student(x), Faculty(x) {
cout<<"TA::TA(int ) called"<< endl;
}
};
int main() {
TA ta1(30);
}
Person::Person(int ) called
Faculty::Faculty(int ) called
Person::Person(int ) called
Student::Student(int ) called
TA::TA(int ) called
#include<iostream>
using namespace std;
class Person {
public:
Person(int x) { cout << "Person::Person(int ) called" << endl; }
Person() { cout << "Person::Person() called" << endl; }
};
class Faculty : virtual public Person {
public:
Faculty(int x):Person(x) {
cout<<"Faculty::Faculty(int ) called"<< endl;
}
};
class Student : virtual public Person {
public:
Student(int x):Person(x) {
cout<<"Student::Student(int ) called"<< endl;
}
};
class TA : public Faculty, public Student {
public:
TA(int x):Student(x), Faculty(x) {
cout<<"TA::TA(int ) called"<< endl;
}
};
int main() {
TA ta1(30);
}
Person::Person() called
Faculty::Faculty(int ) called
Student::Student(int ) called
TA::TA(int ) called
#include<iostream>
using namespace std;
class Person {
public:
Person(int x) { cout << "Person::Person(int ) called" << endl; }
Person() { cout << "Person::Person() called" << endl; }
};
class Faculty : virtual public Person {
public:
Faculty() {
cout<<"Faculty::Faculty(int ) called"<< endl;
}
};
class Student : virtual public Person {
public:
Student() {
cout<<"Student::Student(int ) called"<< endl;
}
};
class TA : public Faculty, public Student {
public:
TA(int x):Student(), Faculty(), Person(x) {
cout<<"TA::TA(int ) called"<< endl;
}
};
int main() {
TA ta1(30);
}
Person::Person(int ) called
Faculty::Faculty(int ) called
Student::Student(int ) called
TA::TA(int ) called
obj.ClassB::a = 10;
obj.ClassC::a = 100;
obj.b = 20;
obj.c = 30;
obj.d = 40;
🟥🟩🟦
#include <iostream>
using namespace std;
void f1() throw (int) {
cout<<"\n f1() Start ";
throw 100;
cout<<"\n f1() End ";
}
void f2() throw (int) {
cout<<"\n f2() Start ";
f1();
cout<<"\n f2() End ";
}
void f3() {
cout<<"\n f3() Start ";
try {
f2();
}
catch(int i) {
cout<<"\n Caught Exception: "<<i;
}
cout<<"\n f3() End";
}
int main() {
f3();
getchar();
return 0;
}
f3() Start
f2() Start
f1() Start
Caught Exception: 100
f3() End
#include <iostream>
using namespace std;
class Test1 {
public:
Test1() { cout << "Constructing an Object of Test1" << endl; }
~Test1() { cout << "Destructing an Object of Test1" << endl; }
};
class Test2 {
public:
Test2() { cout << "Constructing an Object of Test2" << endl;
throw 20; }
~Test2() { cout << "Destructing an Object of Test2" << endl; }
};
int main() {
try {
Test1 t1; // Constructed and destructed
Test2 t2; // Partially constructed
Test1 t3; // t3 is not constructed as this statement never gets executed
} catch(int i) {
cout << "Caught " << i << endl;
}
}
Constructing an Object of Test1
Constructing an Object of Test2
Destructing an Object of Test1
Caught 20
#include <iostream>
using namespace std;
class demo1 {
demo1(){
cout<<"demo1 constructor called"<<endl;
};
class demo2 {
demo2(){
cout<<"demo2 constructor called"<<endl;
};
int main()
{
for (int i = 1; i <= 2; i++) {
try {
if (i == 1)
throw demo1();
else if (i == 2)
throw demo2();
}
catch (demo1 d1) {
cout << "Caught exception of demo1 class \n";
}
catch (demo2 d2) {
cout << "Caught exception of demo2 class \n";
}
}
}
demo1 constructor called
Caught exception of demo1 class
demo2 constructor called
Caught exception of demo2 class
catch (my_error &eObj) { // specifier is a reference type
eObj.status = errCodes::severeErr; // modifies the exception object
throw; // the status member of the exception object is severeErr
}
catch (other_error eObj) { // specifier is a nonreference type
eObj.status = errCodes::badErr; // modifies the local copy only
throw; // the status member of the exception object is unchanged
}
#include <iostream>
using namespace std;
template <typename T>
T myMax(T x, T y)
{
return (x > y) ? x : y;
}
int main()
{
cout << myMax<int>(3, 7) << endl;
cout << myMax<double>(3.0, 7.0) << endl;
cout << myMax<char>('g', 'e') << endl;
return 0;
}
#include <iostream>
using namespace std;
template <typename T>
class Array {
private:
T *ptr;
int size;
public:
Array(T arr[], int s);
void print();
};
template <typename T>
Array<T>::Array(T arr[], int s) {
ptr = new T[s];
size = s;
for(int i = 0; i < size; i++)
ptr[i] = arr[i];
}
template <typename T>
void Array<T>::print() {
for (int i = 0; i < size; i++)
cout<<" "<<*(ptr + i);
cout<<endl;
}
int main() {
int arr[5] = {1, 2, 3, 4, 5};
Array<int> a(arr, 5);
a.print();
return 0;
}
#include<iostream>
using namespace std;
template<class T, class U=char>
class A {
T x;
U y;
public:
A() { cout<<"Constructor Called"<<endl; }
};
int main() {
A<char> a;
A<int, double> b;
return 0;
}
#include <iostream>
using namespace std;
template <class T>
void fun(T a)
{
cout << "The main template fun(): "
<< a << endl;
}
template<>
void fun(int a)
{
cout << "Specialized Template for int type: "
<< a << endl;
}
int main()
{
fun<char>('a');
fun<int>(10);
fun<float>(10.14);
}
#include <iostream>
using namespace std;
template <class T>
class Test
{
public:
Test()
{
// Initialization of data members
cout << "General template object \n";
}
};
template <>
class Test <int>
{
public:
Test()
{
// Initialization of data members
cout << "Specialized template object\n";
}
};
int main()
{
Test<int> a;
Test<char> b;
Test<float> c;
return 0;
}
int *p = NULL;
p = new int;
OR
int *p = new int;
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int *piValue = NULL;
try
{
piValue = new int[9999999999999]; // allocate huge amount of memory
}
catch(...)
{
cout<<"Free memory is not available"<<endl;
return -1;
}
delete []piValue;
return 0;
}
#include <iostream>
#include <new>
using namespace std;
int main() {
int *piValue = NULL;
piValue = new(nothrow) int[999999999999999]; // We are using nothrow here.
if(piValue == NULL) // or if(!piValue)
{
cout<<"Free memory is not available"<<endl;
}
else
{
cout<<"Free memory available"<<endl;
delete []piValue;
}
return 0;
}
void doSomething()
{
int *ptr{ new int{} };
}
int value = 5;
int *ptr{ new int{} }; // allocate memory
ptr = &value; // old address lost, memory leak results
int value{ 5 };
int *ptr{ new int{} }; // allocate memory
delete ptr; // return memory back to operating system
ptr = &value; // reassign pointer to address of value
int *ptr{ new int{} };
ptr = new int{}; // old address lost, memory leak results
unique_ptr<double> p1; // unique_ptr that can point at a double
unique_ptr<int> p2(new int(42)); // p2 points to int with value 42
unique_ptr<string> p1(new string("Stegosaurus"));
unique_ptr<string> p2(p1); // error: no copy for unique_ptr
unique_ptr<string> p3;
p3 = p2; // error: no assign for unique_ptr
// transfers ownership from p1 (which points to the string Stegosaurus) to p2
unique_ptr<string> p2(p1.release()); // release makes p1 null
unique_ptr<string> p3(new string("Trex"));
// transfers ownership from p3 to p2
p2.reset(p3.release()); // reset deletes the memory to which p2 had pointed
#include <iostream>
using namespace std;
#include <memory>
class Rectangle {
int length;
int breadth;
public:
Rectangle(int l, int b)
{
length = l;
breadth = b;
}
~Rectangle() { cout<<"Dest called"<<endl;}
int area()
{
return length * breadth;
}
};
int main()
{
shared_ptr<Rectangle> P1(new Rectangle(10, 5));
cout << P1->area() << endl;
shared_ptr<Rectangle> P2;
P2 = P1;
cout << P2->area() << endl;
cout << P1->area() << endl;
cout << P1.use_count() << endl;
return 0;
}
share_ptr<int> p = make_shared<int>(42);
weak_ptr<int> wp(p); // wp weakly shares with p; use count in p is unchanged
// Here both wp and p point to the same object. Because the sharing is weak, creating wp doesn’t change the reference count of p; it
// is possible that the object to which wp points might be deleted.
if (shared_ptr<int> np = wp.lock()) { // true if np is not null
// inside the if, np shares its object with p
}
#include <iostream>
int main()
{
char **strPtr;
char *str = "Hello!";
strPtr = &str;
delete str;
//strPtr now becomes a dangling pointer
cout<<*strPtr;
strPtr=NULL; // isn't a dangling pointer anymore
}
🟥🟩🟦
#include <iostream>
using namespace std;
typedef unsigned char BYTE;
int main()
{
BYTE b1, b2;
b1 = 'c';
cout << " " << b1;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
auto x = 4;
auto y = 3.37;
auto ptr = &x;
cout << typeid(x).name() << endl
<< typeid(y).name() << endl
<< typeid(ptr).name() << endl;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int fun1() { return 10; }
char fun2() { return 'g'; }
int main()
{
decltype(fun1()) x;
decltype(fun2()) y;
cout << typeid(x).name() << endl;
cout << typeid(y).name() << endl;
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main()
{
int x = 5
decltype(x) j = x + 5;
cout << typeid(j).name();
return 0;
}
#include<bits/stdc++.h>
using namespace std;
void fun(void)
{
cout << "Exiting";
}
int main()
{
atexit(fun);
exit(10);
}
#include<bits/stdc++.h>
using namespace std;
void fun(void)
{
cout << "Exiting";
}
int main()
{
atexit(fun);
_Exit(10);
}
#include <iostream>
using namespace std;
int main(int argc, char** argv)
{
cout << "You have entered " << argc
<< " arguments:" << "\n";
for (int i = 0; i < argc; ++i)
cout << argv[i] << "\n";
return 0;
}
#include <iostream>
using namespace std;
// To handle base case of below recursive Variadic function Template
void print()
{
cout << "I am empty function and "
"I am called at last.\n" ;
}
template <typename T, typename... Types>
void print(T var1, Types... var2)
{
cout << var1 << endl ;
print(var2...) ;
}
int main()
{
print(1, 2, 3.14, "Pass me any "
"number of arguments",
"I will print\n");
return 0;
}
#include<iostream>
using namespace std;
void fun()
{
class Test // local to fun
{
public:
void method() {
cout << "Local Class method() called";
} //method() cannot be defined outside the class even if it is within the function.
};
Test t;
t.method();
}
int main()
{
fun();
return 0;
}
int x,y; // globals
class enclose { // enclosing class
int x; // note: private members
static int s;
public:
class inner { // nested class
void f(int i) {
x = i; // Error: can't write to non-static enclose::x without instance
s = i; // OK: can assign to the static enclose::s
::x = i; // OK: can assign to global x
y = i; // OK: can assign to global y
}
void g(enclose* p, int i) {
p->x = i; // OK: assign to enclose::x
}
};
};
for (auto n : {0, 1, 2, 3, 4, 5})
cout << n << ' ';
int a[] = {0, 1, 2, 3, 4, 5};
for (int n : a)
std::cout << n << ' ';
string str = "Geeks";
for (char c : str)
std::cout << c << ' ';
🟥🟩🟦