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

Basic Oop (College File)

The document contains 16 code snippets demonstrating various object-oriented programming concepts in C++, including: 1. Defining member functions inside and outside a class. 2. Implementing nested member functions. 3. Accessing private member functions from a class. 4. Using static member functions and data members. 5. Creating arrays of objects and passing objects as function arguments. 6. Overloading constructors and using default, copy, and dynamic constructors. 7. Demonstrating the use of new and delete operators and destructors. 8. Implementing association relationships between classes.

Uploaded by

CSD Naman Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views

Basic Oop (College File)

The document contains 16 code snippets demonstrating various object-oriented programming concepts in C++, including: 1. Defining member functions inside and outside a class. 2. Implementing nested member functions. 3. Accessing private member functions from a class. 4. Using static member functions and data members. 5. Creating arrays of objects and passing objects as function arguments. 6. Overloading constructors and using default, copy, and dynamic constructors. 7. Demonstrating the use of new and delete operators and destructors. 8. Implementing association relationships between classes.

Uploaded by

CSD Naman Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 61

1. Write a program for implementing member function outside the class.

#include<iostream>
using namespace std;
class Cube
{
public
:
int side;
int getVolume();

};
int Cube :: getVolume()
{
return side*side*side;
}
int main()
{
Cube obj;
obj.side = 4;
cout<<"Volume of Cube = "<<obj.getVolume()<<endl;
2. Write a program for implementing nesting of member functions.
#include<iostream>
using namespace std;
class nest
{
int a;
int square_num( )
{
return a* a;
}

public:
void input_num( )
{
cout<<"\nEnter a number ";
cin>>a;
}
int cube_num( )
{
return a* a*a;
}

void disp_num()

{
int sq=square_num(); //nesting of member function
int cu=cube_num(); //nesting of member function
cout<<"\nThe square of "<<a<<" is " <<sq;
cout<<"\nThe cube of "<<a<<" is " <<cu;
}
};

int main()

{
nest n1;
n1.input_num();
n1.disp_num();
return 0;
}
3. Program for accessing private member functions from a class.
#include<iostream>
using namespace std;
class A
{
private:
void private_display()
{
cout<<"Private member function of class A";
}
public:
void public_display()
{
private_display();
}
};
int main()
{
A obj;
obj.public_display();
}
4. Program for implementing static member function inside a class.

#include <iostream>
using namespace std;
void Test(){

static int x = 1;
x = ++x;

int y = 1;
y = ++y;
cout<<"x = "<<x<<"\n";
cout<<"y = "<<y<<"\n";
}
int main()
{
Test();
Test();

return 0;
}
5. Write a program for implementing static data member inside the class

#include <iostream>
#include<string.h>
using namespace std;
class Student
{
private:
int rollNo;
char name[10];
int marks;
public:
static int objectCount;
Student()
{
objectCount++;
}

void getdata()
{
cout << "Enter roll number: "<<endl;
cin >> rollNo;
cout << "Enter name: "<<endl;
cin >> name;
cout << "Enter marks: "<<endl;
cin >> marks;
}

void putdata()
{
cout<<"Roll Number = "<< rollNo <<endl;
cout<<"Name = "<< name <<endl;
cout<<"Marks = "<< marks <<endl;
cout<<endl;
}
};
int Student::objectCount = 0;
int main(void) {

Student s1;
s1.getdata();
s1.putdata();

Student s2;

s2.getdata();
s2.putdata();

Student s3;

s3.getdata();
s3.putdata();
cout << "Total objects created = " << Student::objectCount << endl;
return 0;
}
EN E P i ogi a'u° 'J^'*Jg C + +’ de'ete exe
6. Write a program for implementing array of objects.

#include<iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;
class Showroom{
private :
char name[50];
float price;
public :
void getinfo()
{
cout<<"Entre name of bike : ";
cin.getline(name,50);
cout<<"Entre price in lakhs : ";
cin>>price;
}
void display()
{
cout<<"Bike name : "<<name<<endl;
cout<<"Price of bike : "<<price<<" Lakhs"<<endl;
}
};
int main()
{

Showroom obj[20];
int i,size;
cout<<"Entre number of bikes : ";
cin>>size;
for(i=0;i<size;i++)
{
getchar();
obj[i].getinfo();
}
for(i=0;i<size;i++)
{
cout<<"\n\n\n";
obj[i].display();
}
}
7. Write a program for implementing objects as functional arguments.
#include <iostream>
using namespace std;

class Demo
{
private:
int a;

public:

void set(int x)
{
a = x;
}

void sum(Demo ob1, Demo ob2)


{
a = ob1.a + ob2.a;
}

void print()
{
cout<<"Value of A : "<<a<<endl;
}
};

int main()
{
//object declarations
Demo d1;
Demo d2;
Demo d3;

//assigning values to the data member of objects


d1.set(10);
d2.set(20);

//passing object d1 and d2


d3.sum(d1,d2);

//printing the values


d1.print();
d2.print();
d3.print();

return 0;
}
8. Write a program for implementing default constructor.
#include<iostream>

using namespace std;

class student_information
{
public:
int rollno;
string name;
student_information()
{
cout<<"Enter roll number = ";
cin>>rollno;
cout<<"Enter name = ";
cin>>name;

cout<<endl<<"Roll no is = "<<rollno<<endl<<"Name is = "<<name<<endl;


}
};

int main()
{
student_information s;
return 0;
}
E.TP ogfamm IngTC + +odelete.exe
Ente n name = Nam an
Ente c en11 numb ec = 21d
Rod1 no i s = 2T4

Naate T s = Nanan

P nace s s neI u nned 0 ( 0 x0) execuI T I T ate : 5 539 s


an .
P ne s and key’ to cont Tnue .
s
9. Program to implement constructor by passing parameters/

#include<iostream>
using namespace std;

class AREA
{
float radius;
public:
AREA(float r)
{
radius=r;
cout<<"Area of circle = "<<3.14*radius*radius<<endl;
}

};

int main()
{
float r;
cout<<"Enter the radius = ";
cin>>r;
AREA a(r);
return 0;
}
E.TP ogfamm IngTC + +odelete.exe
Enten the radiv s = 69
A n oI c i n c le = ld9d9 . 5
es
10. Program for implementing copy constructor.
#include<iostream>
using namespace std;

class AREA
{
float radius;
public:
AREA(float r)
{
radius=r;

}
float calculatearea()
{
return 3.14*radius*radius;
}

};

int main()
{
float r1,r2;
cout<<"Enter the radius of circle 1= ";
cin>>r1;
cout<<"Enter the radius of circle 2= ";
cin>>r2;
AREA a(r1);
AREA b(r2);
cout<<"\nArea of first circle = "<<a.calculatearea()<<endl;
cout<<"Area of second circle = "<<a.calculatearea()<<endl;
return 0;
}
11. Program for implementing constructor overloading.
#include <iostream>
using namespace std;

class Person
{
private:
int age;

public:
Person()
{
age = 20;
}
Person(int a)
{
age = a;
}

int getAge()
{
return age;
}
};

int main()
{
Person person1, person2(45);

cout << "Person1 Age = " << person1.getAge() << endl;


cout << "Person2 Age = " << person2.getAge() << endl;
return 0;
}
12. Write a program for implementing destructor.

#include <iostream>
using namespace
std; class
HelloWorld
{
public:
HelloWorld()
{
cout<<"Constructor is called"<<endl;
}
~HelloWorld()
{
cout<<"Destructor is called"<<endl;
}
void display()
{
cout<<"Hello World!"<<endl;
}
};
int main()
{
HelloWorld obj;
obj.display();
return 0;
}
E.QPro gla mm IngTC + +odelete.exe
Hello noold
Con st nuc to n T s ca1led
De sI nuc to n T s ca1led

P noc es s netunned 0 ( 0x0) execut hon I Ume - 0 . 031 s


P ne s and key to c ont Tnue .
s
13. Write a program for implementing local class/objects in c++

#include<iostream>
using namespace std;
void fun()
{
class Test // local to fun
{
public:
void method()
{
cout << "Local Class method() called";
}
};

Test t;
t.method();
}

int main()
{
fun();
return 0;
}
E.\P og ammtng\C + +\delete exe

Loc a1 C la ss method ( ca1led


P noc e s s neI unned 0 (0x0) exec ut ion I ime 0 . 028 s
,P ne s s and key to c ont Tnue .
14. Program to show the use of new and delete operator in C++

#include <iostream>
#include <string>
using namespace std;

int main()
{
int *ptr = NULL;
ptr = new int();
int *var = new int(12);

if(!ptr)
{
cout<<"bad memory allocation"<<endl;
}
else
{
cout<<"memory allocated successfully"<<endl;
*ptr = 10;
cout<<"*ptr = "<<*ptr<<endl;
cout<<"*var = "<<*var<<endl;
}

double *myarray = NULL;


myarray = new double[10];
if(!myarray)
{cout<<"memory not allocated"<<endl;}
else
{
for(int i=0;i<10;i++)
myarray[i] = i+1;
cout<<"myarray values : ";
for(int i=0;i<10;i++)
cout<<myarray[i]<<"\t";
}
delete ptr;
delete var;
delete[] myarray;

return 0;
}
15. Write a program for implementing Dynamic Constructor

#include <iostream>
using namespace
std; class geeks
{
const char* p;

public:
geeks()
{
p = new char[6];
p = "geeks";
}

void display()
{
cout << p << endl;
}
};

int main()
{
geeks obj = new geeks();
obj.display();
}
ge eks

Process exited after 0.i0i7 seconds with return value 0


P we ss any key to c ont i nue ..._
16. Program for implementing the association relationship
#include<iostream.h>

class Student;

class Department
{
char* name_p;

public:

Department(char *dName)
{
cout<<"Department::ctor\n";
name_p = new char(sizeof(strlen(dName)));
name_p = dName;
}

char* dName() const


{
return(name_p);
}

~Department()
{
cout<<"Department::dtor\n";
delete(name_p);
}

};

class Student
{
char* name_p;

public:

Student(char *sName)
{
cout<<"Student::ctor\n";
name_p = new char(sizeof(strlen(sName)));
name_p = sName;
}

char* sName()const
{
return(name_p);
}
~Student()
{
cout<<"Student::dtor\n";
delete(name_p);
};
};

class Course
{
Student * std_p;
Department * dept_p;
char * courseName_p;

static unsigned int index;


static Course *courseList[4];

public:

Course(char* crseName, Student* student, Department* dept):


courseName_p(0), std_p(student), dept_p(dept)
{
cout<<"Course:ctor\n";

if (index < 4)
{
courseName_p = new char(sizeof(strlen(crseName)));
courseName_p = crseName;

//insert this Course in courseList


courseList[index] = this;
++index;
}
else
{
cout<<"Cannot accomodate any more Course\n";
}
};

~Course()
{
cout<<"Course:dtor\n";
delete (courseName_p);
};

static char* findStudent(char *crseName, char* deptName)


{
for(int i=0; i<index; i++)
{
if ( (courseList[i]->getCourseName() == crseName) &&
(courseList[i]->getDeptName() == deptName) )
{
return(courseList[i]->getStdName());
}
}
}

char * getStdName()const {return(std_p->sName());};


char * getDeptName() const {return(dept_p->dName());};
char * getCourseName()const {return(courseName_p);};
};

unsigned int Course::index =0;


Course* Course::courseList[4] = {0,0,0,0};

int main()
{
int i;

cout<<"\nExample of Association class...\n";


cout<<" \n\n";

cout<<"We have got 4 students ...\n";


Student *studentNames[4] = {new Student("Meera"), new Student("Moina"), new
Student("Teena"), new Student("Mridula")} ;

cout<<"\n";

cout<<"We have got 2 Departments...\n";


Department *departNames[2] = {new Department("Mathemetics"), new
Department("ComputerSceince")} ;

cout<<"\n";

cout<<"Here class Course Associates Student and Department, with a Course name ...\n";
Course course1("DataStructure",studentNames[0], departNames[1]);
Course course2("Maths",studentNames[3], departNames[0]);
Course course3("Geometry",studentNames[2], departNames[0]);
Course course4("CA",studentNames[1], departNames[1]);

cout<<"\n";

cout<<"Finding a Student using Course and Department...\n";


cout<<"Student who has taken Maths Course in Mathemetics Department
is:"<<Course::findStudent("Maths", "Mathemetics")<<endl;

cout<<"\n";

cout<<"Deletion of objects...\n\n";
for(i=0; i<4; ++i)
{
delete studentNames[i];
}

cout<<"\n";

for(i=0; i<2; ++i)


{
delete departNames[i];
}

cout<<"\n";

return(0);
}
17. Program for implementing the aggregation relationship

#include<iostream.h>

class Employee
{
public:

Employee(char *name)
{ cout<<"Employee::ctor\n
";
myName_p = new char(sizeof(strlen(name)));
myName_p = name;
}

char* disp(){return(myName_p);};

~Employee()
{
cout<<"Employee:dtor\n\n";
delete (myName_p);
}

private:
char *myName_p;
};

class Company
{
public:
Company(char * compName, Employee* emp){
cout<<"Company::ctor\n";
name = new char(sizeof(strlen(compName)));
name = compName;
myEmp_p = emp;
};

~Company()
{
cout<<"Company:dtor\n\n";
myEmp_p = NULL;
};

private:
char *name;
Employee *myEmp_p;
};

int main()
{
cout<<"\nExample of Aggregation Relationship \n";
cout<<" \n\n";

{
cout<<"Here, an Employee-Keerti works for Company-MS \n";
Employee emp("Keerti");

{
Company comp("MS", &emp);
} // here Company object will be deleted, whereas Employee object is still there

cout<<"At this point Company gets deleted...\n";


cout<<"\nBut Employee-"<<emp.disp();
cout<<" is still there\n";

} //here Employee object will be deleted

return(0);
}
18. Program for implementing the composition relationship
#include <iostream>
#include <vector>
using namespace std;

class PageObject {
public:
virtual void Add(PageObject a)
{
}
virtual void Remove()
{
}
virtual void Delete(PageObject a)
{
}
};

class Page : public PageObject {


public:
void Add(PageObject a)
{
cout << "something is added to the page" << endl;
}
void Remove()
{
cout << "soemthing is removed from the page" << endl;
}
void Delete(PageObject a)
{
cout << "soemthing is deleted from page " << endl;
}
};

class Copy : public PageObject


{ vector<PageObject>
copyPages;

public:
void AddElement(PageObject a)
{
copyPages.push_back(a);
}

void Add(PageObject a)
{
cout << "something is added to the copy" << endl;
}
void Remove()
{
cout << "something is removed from the copy" << endl;
}
void Delete(PageObject a)
{
cout << "something is deleted from the copy";
}
};

int main()
{
Page a;
Page b;
Copy allcopy;
allcopy.AddElement(a);
allcopy.AddElement(b);

allcopy.Add(a);
a.Add(b);

allcopy.Remove();
b.Remove();

return 0;
}
19. Program for implementing single level inheritance.
#include<iostream>
using namespace std;
class Area{
protected :
int l,b;
public :
int getarea()
{
cout<<"Area : "<<l*b<<endl;
return l*b;
}
};
class Volume : public Area{
private :
int h;
public :
void setdata(int l ,int b,int h)
{
this->l = l;
this->b = b;
this->h = h;
}
int getvolume()
{
return getarea()*h;
}
};
int main()
{
Volume obj;
int l,b,h;
cout<<"Entre length breadth and hieght : ";
cin>>l>>b>>h;
obj.setdata(l,b,h);
cout<<"Volume : "<<obj.getvolume()<<endl;
}
20. Program for implementing Multilevel inheritance.
#include<iostream>
using namespace std;
class Area{
protected
: int l, b;
public :
int area()
{

return l*b;
}
};
class Volume : public Area{
protected :
int h;
public :
int volume()
{

return area()*h;
}
};
class Density : public Volume{
private :
float m;
public :
void setdata(int l,int b,int h,float m)
{
this->l = l;
this->b = b;
this->h = h;
this->m = m;
}
float density()
{
return m/volume();
}
};
int main()
{
Density obj;
int l,b,h;
float m;
cout<<"Entre l b h and m : ";
cin>>l>>b>>h>>m;
obj.setdata(l,b,h,m);
cout<<"Area : "<<obj.area()<<endl;
cout<<"Volume : "<<obj.volume()<<endl;
cout<<"Density : "<<obj.density()<<endl;
}
21. Program for implementing Multiple inheritance.
#include<iostream>
using namespace std;
class Dim1{
protected :
int l , b;
};
class Dim2 {
protected :
int h;
};
class Volume : public Dim1,public Dim2{
public :
void setdata(int l ,int b, int h)
{
this->l = l;
this->b = b;
this->h = h;
}
int getvolume()
{
return l*b*h;
}
};
int main()
{
Volume obj;
int l , b, h;
cout<<"Entre l b and h : ";
cin>>l>>b>>h;
obj.setdata(l,b,h);
cout<<"Volume : "<<obj.getvolume()<<endl;
}
22. Program for implementing Hierarchical inheritance.
#include<iostream>
using namespace std;
class Parent{
public:
void show()
{
cout<<"show() method of parent class"<<endl;
}
};
class child1 : public Parent{
public :
void display()
{
cout<<"display() method of child1 class"<<endl;
}
};
class child2 : public Parent{
public :
void draw()
{
cout<<"draw() method of child2 class"<<endl;
}
};
int main()
{
child1 c1;
c1.display();
c1.show();
child2 c2;
c2.draw();
c2.show();
}
23. Program for implementing Hybrid inheritance.
#include<iostream>
#include<string.h>
using namespace std;
class Student{
protected :
int rno;
char name[50];
};
class Marks : public Student{
protected :
int p,c,m;
};
class Sessional {
protected :
int in,ex;
};
class Result : public Marks,public Sessional{
public :
void setdata(char name[],int rno,int p,int c,int m,int in,int ex)
{
strcpy(this->name,name);
this->rno = rno;
this->p = p;
this->c = c;
this->m = m;
this->in = in;
this->ex = ex;
}
void display()
{
cout<<"\nStudent details : \n";
cout<<"Name : "<<name<<endl;
cout<<"Roll no : "<<rno<<endl;
cout<<"\n";
cout<<"Physics marks : "<<p<<endl;
cout<<"Chemistry marks : "<<c<<endl;
cout<<"Maths marks : "<<m<<endl;
cout<<"\n";
cout<<"Internal marks : "<<in<<endl;
cout<<"External marks : "<<ex<<endl;
cout<<"\n";
}
void result()
{
int total = p+c+m+in+ex;
cout<<"\n";
cout<<"Total : "<<total<<endl;
double per = total/5.0;
cout<<"Percentage : "<<per<<endl;
}
};
int main()
{

int rno,p,c,m,in,ex;
char name[50];
cout<<"Entre name : ";
cin.getline(name,50);
cout<<"Entre roll number : ";
cin>>rno;
cout<<"Entre p c m marks : ";
cin>>p>>c>>m;
cout<<"Entre int and ext marks : ";
cin>>in>>ex;
Result obj;
obj.setdata(name,rno,p,c,m,in,ex);
obj.display();
obj.result();
}
24. Program for implementing constructor and destructor in inheritance.
#include <iostream>
using namespace
std; class base1
{
public:
base1 (void)
{
cout << " constructor of class base1\n";
}
~base1 ()
{
cout << " destructor of class base1\n";
}
};
class base2
{
public:
base2(void)
{
cout << " constructor of class base2\n";
}
~base2()
{
cout << " destructor of class base2\n";

}
};
class derive1 : public base1, public base2
{
public:
derive1(void)
{
cout << " constructor of class derive1\n";

}
~derive1()
{
cout << " destructor of class derive1\n";
}
};
int main ()
{
derive1 x;
cout << " Destructors are: "<<endl;
}
25. Program for implementing function overloading.
#include <iostream>
using namespace std;
class Addition
{ public:
int sum(int num1,int num2) {
return num1+num2;
}
int sum(int num1,int num2, int num3) {
return num1+num2+num3;
}
};
int main(void) {
Addition obj;
cout<<obj.sum(20, 15)<<endl;
cout<<obj.sum(81, 100, 10);
return 0;
}
26. Program for implementing unary operator overloading.
#include<iostream>
using namespace std;
class Operatordemo{
private :
int a;
public :
Operatordemo()
{
cout<<"Entre value of a : ";
cin>>a;
}
void display()
{
cout<<"Value of a : "<<a<<endl;
}
void operator ++()
{
a = a * 10;
}
void operator --()
{
a = a / 10;
}

};
int main()
{
Operatordemo obj;
obj.display();
++obj;
cout<<"\nAfter overloading :- \n";
obj.display();
--obj;
cout<<"\nAfter overloading :- \n";
obj.display();
}
27. Program for implementing binary operator overloading.
#include<iostream>
#include<string.h>
using namespace std;
class String{
private :
char str[500];
public :
void getdata()
{
cout<<"Entre sting : ";
cin.getline(str,500);
}
void display()
{
cout<<"String : "<<str<<endl;
}
String operator+(String obj2)
{
String obj;
strcat(str,obj2.str);
strcpy(obj.str,str);
return obj;
}
};
int main()
{
String obj1,obj2,obj3;
obj1.getdata();
obj2.getdata();
obj1.display();
obj2.display();
obj3 = obj1 + obj2;
obj3.display();
}
28. Program for implementing dynamic polymorphism.
#include<iostream>
using namespace std;
class Parent{
public :
void show()
{
cout<<"show() method of parent class";
}
};
class child : public Parent{
public :
void show()
{
cout<<"show() method of child class";
}
};
int main()
{
child obj;
obj.show();
}
29. Program for implementing pure Virtual function.
#include<iostream>
#include<conio.h>
using namespace std;
class RBI{//ABSTRACT CLASS
public :
virtual double rate()=0; //PURE VIRTUAL FUNCTION
};
class SBI : public RBI{
public :
double rate()
{
return 1.23;
}
};
class BOI : public RBI{
public :
double rate()
{
return 2.03;
}
};
int main()
{
SBI s;
BOI b;
cout<<"SBI provides :
"<<s.rate()<<endl; cout<<"BOI provied :
"<<b.rate()<<endl; getch();
}
SBI provi d es : 1 . 23
BOI pro i ed 2.B3
30. Program for implementing virtual base class.
#include<iostream.h>
#include<conio.h>

class student {
int rno;
public:

void getnumber() {
cout << "Enter Roll No:";
cin>>rno;
}

void putnumber() {
cout << "\n\n\tRoll No:" << rno << "\n";
}
};

class test : virtual public student {


public:
int part1, part2;

void getmarks() {
cout << "Enter Marks\n";
cout << "Part1:";
cin>>part1;
cout << "Part2:";
cin>>part2;
}
void putmarks() {
cout << "\tMarks Obtained\n";
cout << "\n\tPart1:" << part1;
cout << "\n\tPart2:" << part2;
}
};

class sports : public virtual student {


public:
int score;

void getscore() {
cout << "Enter Sports Score:";
cin>>score;
}

void putscore() {
cout << "\n\tSports Score is:" << score;
}
};

class result : public test, public sports {


int total;
public:

void display() {
total = part1 + part2 + score;
putnumber();
putmarks();
putscore();
cout << "\n\tTotal Score:" << total;
}
};

void main()
{ result obj;
clrscr();
obj.getnumber
();
obj.getmarks(
);
obj.getscore();
obj.display();
getch();
}

You might also like