0% found this document useful (0 votes)
17 views32 pages

Additional Features

Uploaded by

231030021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views32 pages

Additional Features

Uploaded by

231030021
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Additional Features

in C++
Pointer to Class
Members
Defining a Pointer of Class type
class Simple
{
public:
int a;
};

int main()
{
Simple obj;
Simple* ptr; // Pointer of class type
ptr = &obj;

cout << obj.a;


cout << ptr->a; // Accessing member with pointer
}
Here you can see that we have declared a pointer of class type which points to class's object. We can access data
members and member functions using pointer name with arrow -> symbol.
Pointer to Data Members of Class
Using Pointers with Objects
Using Pointers with Objects (example)
class Data
{
public:
int a;
void print()
{
cout << "a is "<< a;
}
};

int main()
{
Data d, *dp;
dp = &d; // pointer to object

int Data::*ptr=&Data::a; // pointer to data member 'a'

d.*ptr=10;
d.print();

dp->*ptr=20;
dp->print();
}
Run-Time Type Identification
Typeid

• The function:
const typeinfo typeid(arg)

returns a const typeinfo object when passed an object, reference, or pointer.

• Typeinfo:

class type_info {
public:
virtual ~type_info();
int operator==(const type_info& rhs) const;
int operator!=(const type_info& rhs) const;
int before(const type_info& rhs) const;
const char* name() const;
const char* raw_name() const;
private:
...
};
Examples of typeid() use

• class foo { … };
typeid(foo).name() returns “foo”

• foo *ptr;
typeid(ptr).name() returns “foo*”
typeid(*ptr).name() returns “foo”

• class derived : public base { … };


typeid(base).before(typeid(derived)) returns true
shape

line circle rectangle

• Shape *sp = new circle;

typeid(shape) == typeid(*sp) returns false


typeid(shape).before(typeid(*sp)) returns true
typeid(sp).name() returns “circle*”
typeid(*sp).name() returns “circle”
dynamic_cast<…>(…)

• Dynamic casts support safe down-casting (casting down an


inheritance hierarchy):
Line* lptr = new line;
circle* cptr = new circle;
rectangle* rptr = new rectangle;
shape* array[3] = { lptr; cptr, rptr };
for(int i=0; i<3; i++)
if(dynamic_cast<circle*>(array[I]))
cout << “circle” << endl;
else
cout << “non-circle” << endl;
Caution

• Typeid and dynamic_cast information is carried in a class’s virtual function pointer table and is intended to
be used only with polymorphic classes, e.g., those with at least one virtual function.

• Typeid works for non-polymorphic classes, but returns only static type info, e.g., based on the static pointer
type, not on the type of the object pointed to.

• You must enable run-time type information (RTTI) in your project settings (C/C++ tab, C++ language
category). Your program will crash if you use dynamic_cast or RTTI and forget to do this.
Namespaces
C++ Mutable Keyword
The mutable storage class specifier in C++ (or use of mutable keyword in C++)
auto, register, static and extern are the storage class specifiers in C. typedef is also considered as
a storage class specifier in C. C++ also supports all these storage class specifiers. In addition to
this C++, adds one important storage class specifier whose name is mutable.

What is the need of mutable?


Sometimes there is requirement to modify one or more data members of class / struct through
const function even though you don’t want the function to update other members of class /
struct. This task can be easily performed by using mutable keyword. Consider this example where
use of mutable can be useful. Suppose you go to hotel and you give the order to waiter to bring
some food dish. After giving order, you suddenly decide to change the order of food. Assume
that hotel provides facility to change the ordered food and again take the order of new food
within 10 minutes after giving the 1st order. After 10 minutes order can’t be cancelled and old
order can’t be replaced by new order. See the following code for details.
#include <bits/stdc++.h>
C++ Mutable Keyword int main()

#include <string.h> // to change the place holder {

using namespace std; void changePlacedOrder(string p) const const Customer c1("Pravasi Meet", "Ice Cream", 3, 100);
{ c1.display();
// Customer Class
placedorder=p; c1.changePlacedOrder("GulabJammuns");
class Customer {
} c1.changeBill(150);
// class Variables
c1.display();
string name;
// change the bill return 0;
mutable string placedorder;
void changeBill(int s) const { bill = s; } }
int tableno;
mutable int bill;
// to display Output
// member methods
void display() const Customer name is: Pravasi Meet
public:
{ Food ordered by customer is: Ice Cream
// constructor cout << "Customer name is: " << name << endl; table no is: 3
Customer(string s, string m, int a, int p) cout << "Food ordered by customer is: " Total payable amount: 100
{ << placedorder << endl; Customer name is: Pravasi Meet
name= s; cout << "table no is: " << tableno << endl; Food ordered by customer is: GulabJammuns
placedorder=m; cout << "Total payable amount: " << bill << endl; table no is: 3
tableno = a; } Total payable amount: 150

bill = p; };

}
C++ Mutable Keyword
• The keyword mutable is mainly used to allow a particular data
member of const object to be modified. When we declare a function
as const, the this pointer passed to function becomes const. Adding
mutable to a variable allows a const pointer to change members.
• mutable is particularly useful if most of the members should be
constant but a few need to be updatable. Data members declared as
mutable can be modified even though they are the part of object
declared as const. You cannot use the mutable specifier with names
declared as static or const, or reference.
Use of explicit keyword in C++
• Explicit Keyword in C++ is used to mark constructors to not implicitly
convert types in C++. It is optional for constructors that take exactly
one argument and work on constructors(with a single argument)
since those are the only constructors that can be used in typecasting.
• We can avoid such implicit conversions as these may lead to
unexpected results. We can make the constructor explicit with the
help of an explicit keyword.
• if we try the following program that uses explicit keywords with a
constructor, we get a compilation error.
explicit keyword in C++ int main()
#include <iostream>
{
using namespace std;
// a Complex object

Complex com1(3.0, 0.0);


class Complex {

private:
if (com1 == 3.0)
double real;
cout << "Same";
double imag;
else

cout << "Not Same";


public:
return 0;
// Default constructor
}
explicit Complex(double r = 0.0,

double i = 0.0) :
Output
real(r), imag(i)

{
Compiler Error : no match for 'operator==' in 'com1 == 3.0e+0‘
}

// A method to compare two //


Complex numbers We receive an error here because to avoid any unexpected errors we have
made our constructor an explicit constructor and 3.0 won’t be converted
bool operator == (Complex rhs) to Complex by our constructor on its own.
{

return (real == rhs.real &&

imag == rhs.imag);

};

You might also like