Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 12

classes:

#include <iostream>
#include <cstring>
using namespace std;
class employee {
char name[80];
public: void putname(char *n);
void getname(char *n);
private: double wage; // now, private again
public: void putwage(double w); // back to public
double getwage();
};
void employee::putname(char *n) { strcpy(name, n); }
void employee::getname(char *n) { strcpy(n, name); }
void employee::putwage(double w) { wage = w; }
double employee::getwage() { return wage; }
int main() {
employee ted;
char name[80];
ted.putname("Ted Jones");
ted.putwage(75000);
ted.getname(name);
cout << name << " makes $";
cout << ted.getwage() << " per year.";
return 0;
}

public data member access in non member func:

#include <iostream>
using namespace std;
class myclass {
public: int i, j, k; // accessible to entire program
};
int main() { myclass a, b;
a.i = 100; // access to i, j, and k is OK
a.j = 4; a.k = a.i * a.j;
b.k = 12; // remember, a.k and b.k are different
cout << a.k << " " << b.k;
return 0;
}

structures:

#include <iostream>
#include <cstring>
using namespace std;
struct mystr { void buildstr(char *s); // public
void showstr();
private: // now go private
char str[255];
} ;
void mystr::buildstr(char *s) {
if(!*s) *str = '\0'; // initialize string
else strcat(str, s);
}
void mystr::showstr() { cout << str << "\n"; }
int main() {
mystr s;
s.buildstr(""); // init
s.buildstr("Hello ");
s.buildstr("there!");
s.showstr();
return 0;
}

In C, structures already provide a means of grouping data. Therefore, it is a small


step to
allow them to include member functions. Second, because structures and classes are
related,
it may be easier to port existing C programs to C++. Finally, although struct and
class are
virtually equivalent today, providing two different keywords allows the definition
of a
class to be free to evolve. In order for C++ to remain compatible with C, the
definition of
struct must always be tied to its C definition.

anonymous unions:
A union can be useful for conserving memory when you have lots of objects and
limited memory.
A union is an object similar to a structure except that all of its members start at
the same
location in memory.

There is a special type of union in C++ called an anonymous union. An anonymous


union does not include a type name, and no objects of the union can be declared.
Instead, an anonymous union tells the compiler that its member variables are to
share the same location. However, the variables themselves are referred to
directly,
without the normal dot operator syntax. For example, consider this program:

local:

#include <iostream>
#include <cstring>
using namespace std;
int main() { // define anonymous union
union { long l; double d; char s[4]; } ;
// now, reference union elements directly
l = 100000; cout << l << " ";
d = 123.2342;
cout << d << " ";
strcpy(s, "hi");
cout << s;
return 0;
}

An anonymous union cannot have protected or private members, and it cannot have
member
functions. A global or namespace anonymous union must be declared with the keyword
static.
Global:
#include <iostream>
using namespace std;
static union {
int a;
int x;
};
int main() {
x=10;
cout<<x;
}

friend function:

It is possible to grant a nonmember function access to the private members of a


class
by using a friend. A friend function has access to all private and protected
members
of the class for which it is a friend. To declare a friend function, include its
prototype
within the class, preceding it with the keyword friend.

A friend function cannot access variables of a class object directly. So, we need
to pass
the class object as a parameter to the function. This passing can be of two types –
Pass by value
Pass by reference

Consider this program:

#include <iostream>
using namespace std;

// forward declaration
class B;
class A {
private:
int numA;
public:
A(): numA(12) { }
// friend function declaration
friend int add(A, B);
};

class B {
private:
int numB;
public:
B(): numB(1) { }
// friend function declaration
friend int add(A , B);
};

// Function add() is the friend function of classes A and B


// that accesses the member variables numA and numB
int add(A objectA, B objectB)
{
return (objectA.numA + objectB.numB);
}

int main()
{
A objectA;
B objectB;
cout<<"Sum: "<< add(objectA, objectB);
return 0;
}
Note:
We use them when we need to operate between two different classes at the same time.

A simple and complete C++ program to demonstrate global friend

Ex 1:

#include <iostream>

using namespace std;

class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};

// Member function definition


void Box::setWidth( double wid ) {
width = wid;
}

// Note: printWidth() is not a member function of any class.


void printWidth( Box box ) {
/* Because printWidth() is a friend of Box, it can
directly access any member of this class */
cout << "Width of box : " << box.width <<endl;
}

// Main function for the program


int main( ) {
Box box;

// set box width with member function


box.setWidth(10.0);

// Use friend function to print the wdith.


printWidth( box );

return 0;
}

Ex 2:
#include <iostream>

class A
{
int a;
public:
A() {a = 0;}
friend void showA(A&); // global friend function
};

void showA(A& x) {
// Since showA() is a friend, it can access
// private members of A
std::cout << "A::a=" << x.a;
}

int main()
{
A a;
showA(a);
return 0;
}

To understand this better, let us consider two classes: Tokyo and Rio. We might
require a
function, metro(), to access both these classes without any restrictions. Without
the friend
function, we will require the object of these classes to access all the members.
Friend
functions in c++ help us avoid the scenario where the function has to be a member
of either
of these classes for access.

Class member as friend function:

#include <iostream>
using namespace std;
class B;

class A {
public:
int a;
public:void Func1( B& b );
};

class B {
private:
int _b;
public:
B()
{
_b=10;
}

// A::Func1 is a friend function to class B


// so A::Func1 has access to all members of B
friend void A::Func1( B& );
};

void A::Func1( B& b ) {a=b._b;


cout<<a<<b._b;
cout<<"this"<<endl;
}
int main()
{
A ob;
B ob1;
ob.Func1(ob1);
cout<<ob.a;
return 0;
}
(B& b) creates variable “b” as a copy of “x,” referencing its value.

As we saw above, we can use pass by reference to modify local variables of a


function.
When you call a function that needs to modify arguments, pass by reference is the
only
way to accomplish this task.

A simple and complete C++ program to demonstrate friend Class

#include <iostream>
class A {
private:
int a;
public:
A() { a=0; }
friend class B; // Friend Class
};

class B {
private:
int b;
public:
void showA(A& x) {
// Since B is friend of A, it can access
// private members of A
std::cout << "A::a=" << x.a;
}
};

int main() {
A a;
B b;
b.showA(a);
return 0;
}

// friend class
#include <iostream>
using namespace std;

class Square;

class Rectangle {
int width, height;
public:
int area ()
{return (width * height);}
void convert (Square a);
};

class Square {
friend class Rectangle;
private:
int side;
public:
Square (int a) : side(a) {}
};

void Rectangle::convert (Square a) {


width = a.side;
height = a.side;
}

int main () {
Rectangle rect;
Square sqr (4);
rect.convert(sqr);
cout << rect.area();
return 0;
}

Advantages of Friend Functions:


A friend function is able to access members without the need of inheriting the
class.
The friend function acts as a bridge between two classes by accessing their private
data.
It can be used to increase the versatility of overloaded operators.
It can be declared either in the public or private or protected part of the class.

Disadvantages of Friend Functions:


Friend functions have access to private members of a class from outside the class
which
violates the law of data hiding.
Friend functions cannot do any run-time polymorphism in their members.

Important Points About Friend Functions and Classes:


Friends should be used only for limited purposes. Too many functions or external
classes
are declared as friends of a class with protected or private data access lessens
the value
of encapsulation of separate classes in object-oriented programming.
Friendship is not mutual. If class A is a friend of B, then B doesn’t become a
friend of
A automatically.
Friendship is not inherited.
The concept of friends is not in Java.

default constructor:
#include <iostream>
using namespace std;
class A {
int x;
char b;
public:
A()
{x=0;
b='c';
}
void display(){
cout<<x<<b;
}
};
int main() {
A a;
a.display();
return 0;
}

Different way of initialization within a constructor:

#include<iostream>
using namespace std;
class A{
int a;
float b;
public:
A():a(3),b(4.7)
{
cout<<a<<b;
}
};
int main()
{
A ob;
return 0;
}

parameterised constructor:

#include <iostream> using namespace std;


class myclass { int a, b; public: myclass(int i, int j) {a=i; b=j;} void show()
{cout << a << " " << b;} };
int main() { myclass ob(3, 5);
ob.show();
return 0;
}

Default values in the constructor:

#include <iostream>
using namespace std;
class myclass { int a, b;
public: myclass(int i=4, int j=5) {a=i; b=j;}
void show() {cout << a << " " << b;} };
int main() {
myclass ob(3),ob1,ob2(2,9);
ob.show();
ob1.show();
ob2.show();
return 0;
}

static data members:

#include <iostream> using namespace std;


class shared { public: static int a; } ;
int shared::a; // define a
int main() { // initialize a before creating any objects
shared::a = 99;
cout << "This is initial value of a: " << shared::a;
cout << "\n";
shared x;
cout << "This is x.a: " << x.a;
return 0;
}

To keep track of num of objects:

#include <iostream>
using namespace std;
class Counter {
public: static int count;
Counter() { count++; }
~Counter() { count--; }
};
int Counter::count;
void f();
int main(void) {
cout << Counter::count << "\n";
Counter o1;
cout << "Objects in existence: ";
cout << Counter::count << "\n";
Counter o2;
cout << "Objects in existence: ";
cout << Counter::count << "\n";
f();
cout << "Objects in existence: ";
cout << Counter::count << "\n";
return 0;
}
void f() {
Counter temp;
cout << "Objects in existence: ";
cout << Counter::count << "\n"; // temp is destroyed when f() returns
}

Static member functions:

#include <iostream>
using namespace std;
class Complex { int a;
static int b;
public:
static void display(){
cout<<b;
}
};
int Complex::b=0;
int main() {
Complex c;
Complex::display();
return 0;
}

this pointer:

this is a keyword that refers to the current instance of the class.


Every object in C++ has access to its own address through an important pointer
called
this pointer. The this pointer is an implicit parameter to all member functions.
Therefore, inside a member function, this may be used to refer to the invoking
object.

#include<iostream>
using namespace std;

/* local variable is same as a member's name */


class Test
{
private:
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;
}

Arrow operator:

The dot operator is applied to the actual object. The arrow operator is used with a
pointer
to an object

#include <iostream>
using namespace std;
class emp { int a; float b;
public:emp ( int b, float c): a(b),b(c)
{cout << " Constructor " ;}
~emp(){ cout << " Destructor " ;}
void disp(){ cout << " In Display " ;
cout << a <<b;
}
};
int main(){
emp *e = new emp(20,1.5);
cout<<e<<&e<<endl;
e->disp();
}

The Scope Resolution Operator:

int i; // global i
void f()
{
int i; // local i
i = 10; // uses local i
.
.
.
}
As the comment suggests, the assignment i = 10 refers to the local i. But what if
function f( ) needs to access the global version of i? It may do so by preceding
the
i with the :: operator, as shown here.
int i; // global i
void f()
{
int i; // local i
::i = 10; // now refers to global i
.
.
.
}

Nested Classes
It is possible to define one class within another. Doing so creates a nested class.
Since
a class declaration does, in fact, define a scope, a nested class is valid only
within
the scope of the enclosing class.

Local Classes
A class may be defined within a function. For example, this is a valid C++ program:
#include <iostream>
using namespace std;
void f();
int main()
{
f();
// myclass not known here
return 0;
}
void f()
{
class myclass {
int i;
public:
void put_i(int n) { i=n; }
int get_i() { return i; }
} ob;
ob.put_i(10);
cout << ob.get_i();
}

Several restrictions apply to local classes.


First, all member functions must be defined within the class declaration.
The local class may not use or access local variables of the function in which it
is
declared.
No static variables may be declared inside a local class. Because of these
restrictions,
local classes are not common in C++ programming.

Object Assignment:

// Assigning objects.
#include <iostream>
using namespace std;
class myclass {
int i;
public:
void set_i(int n) { i=n; }
int get_i() { return i; }
};
int main()
{
myclass ob1, ob2;
ob1.set_i(99);
ob2 = ob1; // assign data from ob1 to ob2
cout << "This is ob2's i: " << ob2.get_i();
return 0;
}

You might also like