Assignments For C++
Assignments For C++
1) I) allocate memory for 1 int and store 420 value inside. now release it.
Answer –
#include <iostream>
using namespace std;
int main() {
int* ptr = new int;
*ptr = 420;
cout << "Value: " << *ptr << endl;
delete ptr;
return 0;
}
II) allocate memory for 10 characters on heap store 10 characters ,display them and release that
memory.
Answer-
#include <iostream>
using namespace std;
int main() {
// Allocate memory for 10 characters
char* ch = new char[10];
// Store 10 characters (A to J)
for (int i = 0; i < 10; i++) {
ch[i] = 'A' + i;
}
return 0;
}
2) define a class to meet following requirements
First f3;
f3=f1 f3.disp
make sure neither memory leak nor dangling pointer arises in the code
Answer-
#include <iostream>
#include <string> // use string instead of char*
using namespace std;
class First {
string str1;
string str2;
public:
// Default constructor
First() : str1(""), str2("") {}
// Parameterized constructor
First(const string& s1, const string& s2) : str1(s1), str2(s2) {}
// Display function
void disp() const {
cout << "str1: " << str1 << ", str2: " << str2 << endl;
}
};
int main() {
First f1("hello", "welcome");
f1.disp();
return 0;
}
3) define a class “Voter”,its members should be int id, char *name, char *address.
Define input() , show() methods , Accept from user , how many voters he has .
[DMA], Depending upon that , allocate the memory,invoke input() and get the data from user.
Now invoke show method for all the objects created. make sure neither memory leak nor dangling
pointer arises in the code
Answer –
#include <iostream>
#include <cstring>
using namespace std;
class Voter {
int id;
char* name;
char* address;
public:
// Default constructor with initialization
Voter() {
id = 0;
name = new char[1];
name[0] = '\0';
// Destructor
~Voter() {
delete[] name;
delete[] address;
}
// Show method
void show() const {
cout << "ID: " << id << ", Name: " << name << ", Address: " << address << endl;
}
};
int main() {
int n;
cout << "How many voters? ";
cin >> n;
delete[] voters;
return 0;
}
4) Sample s1(10)
s1-300
s1=600
int data=s1
s1+s2
++s1
s1++
s1+=20
100+s1
cin>>s1
cout<<s1
Answer –
#include <iostream>
using namespace std;
class Sample {
int value;
public:
// Constructor
Sample(int v = 0) : value(v) {}
// Operator overloading
Sample operator-(int x) const {
return Sample(value - x);
}
Sample& operator=(int x) {
value = x;
return *this;
}
Sample& operator+=(int x) {
value += x;
return *this;
}
// int + Sample
Sample operator+(int x, const Sample& s) {
return Sample(x + s.value);
}
// Output
ostream& operator<<(ostream& out, const Sample& s) {
out << s.value;
return out;
}
// Input
istream& operator>>(istream& in, Sample& s) {
in >> s.value;
return in;
}
int main() {
Sample s1(10), s2(5), s3;
s1 = 600; // assignment
cout << "s1 = " << s1 << endl;
s1 = s1 - 300; // subtraction
cout << "s1 - 300 = " << s1 << endl;
s3 = s1 + s2; // addition
cout << "s1 + s2 = " << s3 << endl;
++s1; // pre-increment
cout << "++s1 = " << s1 << endl;
s1++; // post-increment
cout << "s1++ = " << s1 << endl;
s1 += 20; // operator +=
cout << "s1 += 20 = " << s1 << endl;
return 0;
}
5) RTTI virtual or pure virtual function collect child class addresses in parent pointer, child class
object in parent reference, array of parent pointers storing addresses of child classes dynamic_cast
Answer –
#include <iostream>
#include <typeinfo>
using namespace std;
class Base {
public:
virtual void show() { cout << "Base show()\n"; }
virtual ~Base() {}
};
int main() {
// 1. Parent pointer to child object
Base* ptr = new Derived();
ptr->show();
// 4. RTTI - typeid
cout << "Type of ptr: " << typeid(*ptr).name() << endl;
// 5. dynamic_cast
Derived* down = dynamic_cast<Derived*>(ptr);
if (down) {
cout << "Downcast successful\n";
down->derivedOnly();
}
else {
cout << "Downcast failed\n";
}
// Clean up
delete ptr;
delete arr[0];
delete arr[1];
return 0;
}
6)
class B
int y;
class A
int x;
void disp1(){}
Answer-
#include <iostream>
using namespace std;
class B {
int y;
public:
void disp2(A* a); // declare function that accepts A*
};
class A {
int x;
public:
A(int a) { x = a; }
friend class B; // allow B to access private members
void B::disp2(A* a) {
cout << "Accessing A's x from B: " << a->x << endl;
}
int main() {
A a1(100);
B b1;
b1.disp2(&a1);
return 0;
}
7) Given
class A
private:
int len;
};
while creating object of above class pass int array and its length
make sure when you call disp , it should display the whole array which was passed while creating
array
also make sure you can perform following operations on the objects of class A
ref1[0]=1000;
Answer-
#include <iostream>
using namespace std;
class A {
private:
int* ptr; // dynamic array
int len;
public:
// Constructor: takes an array and its length
A(int arr[], int l) {
len = l;
ptr = new int[len];
for (int i = 0; i < len; i++) {
ptr[i] = arr[i];
}
}
// Display function
void disp() {
for (int i = 0; i < len; i++) {
cout << ptr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = { 10, 20, 30, 40, 50 };
A ref1(arr, 5);
ref1[0] = 1000;
cout << "After changing ref1[0] to 1000: ";
ref1.disp();
return 0;
}
Day 7 Assignment : C++
/*
1) Create a base class Weapon. Define virtual function “void attack()” in it.
“Rifle” class will have one more function “Chambering ()”. create an array of pointer
to Weapon having 3 elements.
In this array , store the instances of child classes.
Traverse the array , find out where exactly “Rifle” is stored using RTTI (dynamic_cast) , and
invoke “Chambering ()” function along with “attack()” function.
*/
#include<iostream>
// heirarchical inheritance
public:
virtual void attack() // virtual method i.e. late binding (content checked)(so all child
methods will be virtual automatically )
};
public:
void attack() override // override keyword is used i.e. if you define method with
different arguments , you will get error
};
public:
void attack() override // override keyword is used i.e. if you define method with
different arguments , you will get error
}
};
public:
void attack() override // override keyword is used i.e. if you define method with
different arguments , you will get error
};
int main()
arr[i]->attack();
Rifle *d = dynamic_cast<Rifle*>(arr[i]);
d->Chambering();
}
return 0;
o/p,
/*
2) Create a base class Animal. Declare pure virtual function “void makeSound()” in it.
create a global function “void perform() which accepts pointer of type Animal so that it can
invoke “makeSound()” function polymorphically.
Inside this function find out where exactly where “Tiger” is stored using RTTI (dynamic_cast) ,
and invoke “hunting()” function along with “makeSound()” function.
*/
#include<iostream>
public:
};
};
{
cout << "Cat meows " << endl;
};
public:
};
// global function “void perform() which accepts pointer of type Animal so that it can invoke
“makeSound()” function polymorphically
// find out where exactly where “Tiger” is stored using RTTI (dynamic_cast)
Tiger *T=dynamic_cast<Tiger*>(ptr);
T->hunting();
int main()
return 0;
o/p,
/*
3) Create a base class Cricket. Define virtual function “void play()” in it.
create a global function “void doit() which accepts reference of type Cricket so that it can
invoke “play()” function polymorphically.
Inside this function find out where exactly where “Test” is stored using RTTI (dynamic_cast) ,
and invoke “daywise_summary()” function along with “play()” function. [ handle bad_cast
exception ]
*/
#include<iostream>
public:
}
};
};
public:
void daywise_summary()
};
cout << "It will be a Twenty over Cricket match " << endl;
};
// global function “void doit() which accepts reference of type Cricket so that it can invoke
“play()” function polymorphically
// find out where exactly where “Test” is stored using RTTI (dynamic_cast)
// invoke “daywise_summary()” function along with “play()” function. [ handle
bad_cast exception ]
Test T = dynamic_cast<Test&>(ref);
T.daywise_summary();
cout << "in catch block " << r.what() << endl; // what is a
function
int main()
// objects created
FiftyOver obj1;
TwentyOver obj2;
Test obj3;
doit(obj1);
doit(obj2);
doit(obj3);
return 0;
o/p,
4)Create a base class Cricket. Declare pure virtual
function “void play()” in it.
Define following sub classes for this class.
A) FiftyOver b) Test c) TwentyOver
“Test” class will have one more function
“daywise_summary()”.
Create an array of pointer
to “Cricket” class having 3 elements. Store child class
objects into this array.
Now using using RTTI , find out where is “Test”,
and call “daywise_summary()” along with “play()”
function.
/*
4) Create a base class Cricket. Declare pure virtual function “void play()” in it.
Create an array of pointer to “Cricket” class having 3 elements. Store child class objects into
this array.
Now using using RTTI , find out where is “Test”, and call “daywise_summary()” along with
“play()” function.
*/
#include<iostream>
public:
};
};
public:
}
void daywise_summary() // extra method
cout << "This is day wise summary of test match " << endl;
};
};
int main()
Cricket* arr[3];
Test obj1;
FiftyOver obj2;
TwentyOver obj3;
arr[0] = &obj1;
arr[1] = &obj2;
arr[2] = &obj3;
// Now using using RTTI, find out where is “Test”, and call “daywise_summary()” along
with “play()” function.
arr[i]->play();
if (ptr)
{
ptr->daywise_summary();
return 0;
o/p,
/*
A) HardDisk b) CD c) PenDrive.
now write a global function "perform()" which will accept "StorageDevice class reference" as
an argument.
In this function using RTTI invoke "store()" method of only “PenDrive”. [ handle bad_cast
exception ]
From main function try to call “perform()” function by passing various child classes.
*/
#include<iostream>
class StorageDevice
{
public:
};
// A) HardDisk b) CD c) PenDrive.
public:
};
public:
};
public:
};
// global function "perform()" which will accept "StorageDevice class reference" as an
argument.
try
p.store();
cout << "Not a Pendrive object: " << e.what() << endl;
int main()
Pendrive p;
CD c;
HardDisk h;
// passing objects
return 0;
o/p,
6) Create a base class “Subject”.Declare pure
virtual function “void maxmarks()” in it. Define
following sub classes for this class. A) Maths b)
History c) English. Define “maxmarks” in these
classes. In main function, create array of pointer
to Subject, which will contain objects of these
three sub classes. Using RTTI, find out where is
“History” and call its maxmarks() method.
-
/*
In main function, create array of pointer to Subject, which will contain objects of these three
sub classes.
Using RTTI, find out where is “History” and call its maxmarks() method.
*/
#include<iostream>
class Subject
public:
};
public:
};
public:
};
public:
};
//,
//
int main()
Subject* arr[3];
English E;
History H;
Maths M;
arr[0] = &E;
arr[1] = &H;
arr[2] = &M;
// Using RTTI, find out where is “History” and call its maxmarks() method.
History* H = dynamic_cast<History*>(arr[i]);
if (H)
H->maxmarks();
}
}
return 0;
o/p,
OOPS
constructors
default,parameterized
copy constructor
array of object
answer-
// Only if using Visual Studio; optional
#include <iostream>
#include <cstring>
using namespace std;
class Student {
private:
char* name;
int age;
public:
// Default Constructor
Student() {
name = new char[1];
name[0] = '\0';
age = 0;
cout << "Default Constructor Called\n";
}
// Parameterized Constructor
Student(const char* n, int a) {
name = new char[strlen(n) + 1];
strcpy_s(name, strlen(n) + 1, n); // Safe version of strcpy
age = a;
cout << "Parameterized Constructor Called\n";
}
// Destructor
~Student() {
cout << "Destructor Called for: " << name << endl;
delete[] name;
}
void show() {
cout << "Name: " << name << ", Age: " << age << endl;
}
};
int main() {
cout << "Stack Object:\n";
Student s1("Alice", 21); // stack object
s1.show();
return 0;
}
Friend function
forward declaration
Answer-
#include <iostream>
using namespace std;
class A {
private:
int a;
public:
A(int val) { a = val; }
public:
B(int val) { b = val; }
int main() {
A obj1(10);
B obj2(20);
showSum(obj1, obj2); // Accesses private data from both classes
return 0;
}
Operator Overloading
assignment
pre-post increment/decrement
> , <, ==
compound assignment
answer-
#include <iostream>
using namespace std;
class Sample {
int value;
public:
// Constructors
Sample() : value(0) {}
Sample(int v) : value(v) {}
// Display
void show() const { cout << "Value: " << value << endl; }
// Assignment operator
Sample& operator=(const Sample& other) {
value = other.value;
return *this;
}
// Pre-increment (++obj)
Sample& operator++() {
++value;
return *this;
}
// Post-increment (obj++)
Sample operator++(int) {
Sample temp = *this;
value++;
return temp;
}
// Pre-decrement (--obj)
Sample& operator--() {
--value;
return *this;
}
// Post-decrement (obj--)
Sample operator--(int) {
Sample temp = *this;
value--;
return temp;
}
// Arithmetic operators
Sample operator+(const Sample& s) const {
return Sample(value + s.value);
}
// Comparison operators
bool operator>(const Sample& s) const { return value > s.value; }
bool operator<(const Sample& s) const { return value < s.value; }
bool operator==(const Sample& s) const { return value == s.value; }
// Insertion operator
ostream& operator<<(ostream& out, const Sample& s) {
out << s.value;
return out;
}
// Primitive on left
Sample operator+(int num, const Sample& s) {
return Sample(num + s.value);
}
int main() {
Sample s1(10), s2(20), s3;
return 0;
}
conversion
answer-
#include <iostream>
using namespace std;
class Distance {
int meter;
public:
// Default constructor
Distance() : meter(0) {}
void display() {
cout << "Distance = " << meter << " meters\n";
}
};
int main() {
// Primitive to user-defined
int x = 50;
Distance d1; // Default object
d1 = x; // Implicit call to constructor
d1.display();
// User-defined to primitive
int y;
y = d1; // Implicit call to operator int()
cout << "Converted int value = " << y << endl;
return 0;
}
answer-
#include <iostream>
using namespace std;
virtual ~Animal() {
cout << "Animal destroyed\n";
}
};
// Derived class 1
class Dog : public Animal {
public:
void speak() override {
cout << "Dog says: Woof!\n";
}
~Dog() {
cout << "Dog destroyed\n";
}
};
// Derived class 2
class Cat : public Animal {
public:
void speak() override {
cout << "Cat says: Meow!\n";
}
~Cat() {
cout << "Cat destroyed\n";
}
};
int main() {
Animal* a1 = new Dog(); // Base class pointer → Dog object
Animal* a2 = new Cat(); // Base class pointer → Cat object
a1->speak(); // Dog's speak
a1->sound(); // Dog's sound
delete a1;
delete a2;
return 0;
}
answer-
#include <iostream>
using namespace std;
class Base {
public:
virtual void show() {
cout << "Base class show()" << endl;
}
virtual ~Base() {}
};
int main() {
Derived d;
return 0;
}
parent class array stores child class objects
answer-
class Parent {
public:
virtual void speak() {
cout << "Parent speaking" << endl;
}
virtual ~Parent() {}
};
int main() {
// Array of Parent class pointers
Parent* arr[3];
// Polymorphic calls
for (int i = 0; i < 3; i++) {
arr[i]->speak();
}
return 0;
}
function to accept parent class pointer and polymorphically invokes virtual or pure virtual function/s.
#include <iostream>
using namespace std;
class Parent {
public:
virtual void show() {
cout << "Parent show()" << endl;
}
virtual ~Parent() {}
};
int main() {
Parent p;
Child c;
return 0;
}
Example with pure virtual function (Abstract class):
#include <iostream>
using namespace std;
class Parent {
public:
virtual void show() = 0; // pure virtual function = abstract class
virtual ~Parent() {}
};
void display(Parent* p) {
p->show(); // polymorphic call
}
int main() {
// Parent p; // Error: cannot create object of abstract class
Child c;
return 0;
}
function to accept parent class reference and polymorphically invokes virtual or pure virtual
function/s.
answer-
class Parent {
public:
virtual void show() {
cout << "Parent show()" << endl;
}
virtual ~Parent() {}
};
int main() {
Parent p;
Child c;
return 0;
}
Example with pure virtual function (Abstract class):
#include <iostream>
using namespace std;
class Parent {
public:
virtual void show() = 0; // pure virtual function
virtual ~Parent() {}
};
void display(Parent& p) {
p.show(); // polymorphic call
}
int main() {
// Parent p; // Error: cannot instantiate abstract class
Child c;
return 0;
}
#include <iostream>
#include <typeinfo> // for std::bad_cast
using namespace std;
class Base {
public:
virtual void show() { cout << "Base class\n"; }
virtual ~Base() {}
};
int main() {
Base b;
Derived d;
return 0;
}
Imp note:
program should not give any dangling pointer and memory leak problem, then you must
and
class MyString {
char* str;
public:
MyString(const char* s = "") {
str = new char[strlen(s) + 1];
// Use strcpy_s(destination, size, source)
strcpy_s(str, strlen(s) + 1, s);
}
~MyString() {
delete[] str;
cout << "Destructor called\n";
}
int main() {
MyString s1("Hello");
MyString s2 = s1;
s1.show();
s2.show();
return 0;
}