C SlidesFor2015-2016Batch
C SlidesFor2015-2016Batch
C SlidesFor2015-2016Batch
Const-ness
Reference Data Type
Inline Functions
Default Function Parameters
Function Overloading & Resolution
Dynamic Memory Allocation
Examples of Declaration
int j = 5;
int& i = j;
Returning a reference
return value is not copied back
may be faster than returning a value
calling function can change returned object
cannot be used with local variables
return 0;
}
Disadvantages:
Parameter passing mechanism is not robust and
frequently leads to errors.
Type checking during parameter passing is not done
Typical Use:
Small code re-use
Slide: 12 Matangini Chattopadhyay
Inline Functions
Inline functions act like functions
They can be class members
Type checking is performed
They can be overloaded
They obey normal parameter passing rules
But they are implemented like macros
Code is substituted inline, not called
Use is faster than calling a function
Use may take more space
They are defined in .h files, not in .c/.cxx files
2. Standard Conversion
void print(int); void print(char *);
void set (int *);
void set (const char *);
int main()
{
print (0); //Which print?
set (0); //Which set?
}
Class Members
Constructor & Destructor
Friends
Static Members
Struct & Union
int main ()
{
Employee e1; Employee *e2;
e2 = new Employee;
e1.setName(Amit); e2->name = strdup(Ashis"); // Error
e2.setSalary(29100); e2->setSalary(29100);
}
Re-look at
void setName (const char *x) { name = strdup(x); }
Whose name?
void setName (const char *x) { this->name = strdup(x); }
private :
char *data; String concat(char *left, String *right)
int len; {
} ; String both[strlen(left) + right->len + 1];
strcpy(both.data, left);
String::String(int len)
strcat(both.data, right->data);
{
return both;
this->len = len;
}
data = new char[len+1];
data[len] = \0;
}
friends. int n;
} ;
Friend-ship is neither class Matrix {
.
Solution
. Change the return type to
. String &
Bug:
Self Assignment will cause problem
Solution:
Check the following condition and return if false.
if (this != rhs) .
Suppose that we have a class Integer & operator*(Integer &lhs, Integer &rhs)
class B {
public:
operator A () const;
};
void f(const A &);
B b;
f(b); //Error - Ambiguous