Virtual Function: #Include #Include
Virtual Function: #Include #Include
#include <iostream.h>
#include <conio.h>
class Base {
public:
virtual void display() {
cout << "Base class display function" <<
endl;
}
};
Base baseObj;
Derived derivedObj;
basePtr = &baseObj;
basePtr->display();
basePtr = &derivedObj;
basePtr->display();
getch();
}
Output:
Early Binding
#include <iostream.h>
#include<conio.h>
class A {
public:
void display() {
cout << "Base class is invoked" << endl;
}
};
class B : public A {
public:
void display() {
cout << "Derived class is invoked" << endl;
}
};
int main() {
A a; // object of base class
B b; // object of derived class
a.display();
b.display();
getch();
}
Output:
Late Binding
#include <iostream.h>
#include <conio.h>
class A {
public:
virtual void display() {
cout << "Base class is invoked" << endl;
}
};
class B : public A {
public:
void display() {
cout << "Derived class is invoked" << endl;
}
};
int main() {
A* a; /
B b;
a = &b;
a->display();
getch();
}
Output:
Function Overriding
#include <iostream.h>
#include <conio.h>
class Animal {
public:
void makeSound() {
cout << "Animal makes a sound." << endl;
}
};
animal.makeSound();
dog.makeSound();
getch();
}
Output:
Friend Function
#include <iostream.h>
#include <conio.h>
class MyClass {
private:
int data;
public:
MyClass(int d) : data(d) {}
friend void printData(const MyClass& obj);
};
void main() {
int value;
cout << "Enter a value: ";
cin >> value;
MyClass obj(value);
printData(obj);
getch();
}
Output:
Inline Function
#include <iostream.h>
#include <conio.h>
inline int square(int num)
{
return num * num;
}
void main()
{
int number;
cout << "Enter a number: ";
cin >> number;
cout << "Square of the number: " <<
square(number) << endl;
getch();
}
Output:
File Handling (Write Function)
#include<iostream.h>
#include<conio.h>
#include<fstream.h>
int main()
{
char arr[100];
myfile<<arr;
myfile.close();
cout<<"File write operation performed
successfully"<<endl<<endl;
getch();
}
Output:
File Handling (Read Function)
#include <iostream.h>
#include <conio.h>
#include <fstream.h>
int main()
{
char filename[50];
cout << "Enter the name of the file to read: ";
cin.getline(filename, 50);
ifstream inputFile(filename);
// Open file for reading
if (inputFile)
{
char data[100];
while (!inputFile.eof())
{
inputFile.getline(data, 100);
cout << data << endl;
}
inputFile.close(); // Close the file
}
else {
cout << "Failed to open the file." << endl;
getch();
}
Output: