OOPs in C++ Codes
Friend functions Example:
#include<bits/stdc++.h>
using namespace std;
//Forward Definition Needed
class BaseClass;
class OtherClass{
public:
void memberFunction(BaseClass &obj);
};
class BaseClass{
private:
string private_string = "This is private variable";
protected:
string protected_string = "This is protected variable";
public:
string public_string = "This is public variable";
friend class FriendClass;
friend void friendFunction(BaseClass &obj);
friend void OtherClass::memberFunction(BaseClass &obj);
};
class FriendClass{
public:
void display(BaseClass &obj){
cout<<"Start FriendClass\n";
cout<<obj.private_string<<endl;
cout<<obj.protected_string<<endl;
cout<<obj.public_string<<endl;
cout<<"End FriendClass\n\n";
}
};
void OtherClass::memberFunction(BaseClass &obj){
cout<<"OtherClass Starts\n";
cout<<obj.private_string<<endl;
cout<<obj.protected_string<<endl;
cout<<obj.public_string<<endl;
cout<<"OtherClass Ends\n\n";
}
void friendFunction(BaseClass &obj){
cout<<"Start Friendfunction\n";
cout<<obj.private_string<<endl;
cout<<obj.protected_string<<endl;
cout<<obj.public_string<<endl;
cout<<"End FriendFunction\n\n";
}
int main(){
BaseClass base;
FriendClass f;
OtherClass oc;
f.display(base);
friendFunction(base);
oc.memberFunction(base);
return 0;
}
Constructors:
#include<bits/stdc++.h>
using namespace std;
class Students{
public:
int rollNo,age;
string name;
int *check = new int;
Students(string s);
//constructor inside class
Students(){
cout<<"Enter Name: \n";
cin>>name;
cout<<"Enter RollNo: \n";
cin>>rollNo;
age = 21;
* check = 123;
cout<<endl;
}
~Students(){
cout<<"Deletd\n";
}
};
// Constructor OutSide Class
Students::Students(string s){
name = s;
rollNo = 5000;
age = 22;
}
int main(){
Students raunit;
cout<<raunit.name<<endl;
Students other("Verma");
cout<<other.name<<endl;
Students raunitCopy(raunit);
// shallow copy example
*raunit.check=321;
cout<<*raunitCopy.check<<endl;
return 0;
}
Local Classes:
#include<iostream>
using namespace std;
// can be accessed inside local class
int raunit = 82;
void fun(){
// local class functions can only access static and enum inside function
static int a = 10;
// cannot be accessed inside the class
// int a = 234;
class localClass{
public:
int num = 10;
// cannot contain static member
// static int i;
static void myfun(){
cout<<raunit<<endl;
cout<<"Static fun inside local class\n";
}
void test();
};
// cannot be used outside class in local function
// void localClass::test(){ }
localClass l;
localClass::myfun();
cout<<l.num<<endl;
}
int main()
{
fun();
return 0;
}
https://mega.nz/folder/wiImDYxS#LeGweeHxeReKRErGLgovIw
Other:
0 Comments
If you have any doubts/suggestion/any query or want to improve this article, you can comment down below and let me know. Will reply to you soon.