Skip to main content

Posts

Showing posts from July, 2019

FUN with the FUNCTIONS in C++

1. To define a function outside the class, there MUST be a prototype inside the class.
For eg.
class Jg{
int num;
public:
Jg(){ num=0; }
};
void Jg::Display() //Error will be here
{ cout<<num;
}
//This Program will give the error "no 'void Jg::Display()' member function declared in class 'Jg'"

2. What if one member function defined twice, once inside class and once outside?
Will give error "[error]redefintion of int Jg::Display()"
And then pointing on the first defintion it will give "[NOTE] int Jg::Display() previously defined here"
PROGRAM - #include<iostream>
using namespace std;
class Jg{
int num;
public:
Jg(){
num=0;
}
Display(){
cout<<"Hello";
}
};
int Jg::Display(){ //ERROR
cout<<num;
}
main(){
Jg J1;
J1.Display();
}

3. What if a member function declared twice inside the class?
Will show error "int Ag::Display() cannot be overloaded"
Program- #include<iostream>
using namespace std;
class Ag{
int n…

Interesting Inferences about strings in C++ (and related library functions)

1. strlen() FUNCTION OF string.h It stops counting where it finds uninitialised character (ie if Arr[i] is uninitialised, it gives length as i)
for eg. char S[10];
S[0]='c';
cout<<strlen(S); //This prints '1'
for eg. char S[10];
S[4]='c';
cout<<strlen(S); //This prints '0', even though there is one character

NOTE- Though such case may not be ever encountered in actual use but i just found this out experimenting with the code

Reason- See the function definition of strlen() in string (or string.h on older ones) header file

2. THE NULL CHARACTER The null character (that terminates strings, ie '\0') has the integer code '0'.
(i. cout<<int('\0'); gives 0)
'\n' has code 10
' ' has code 32
txt files terminate with a character with code '-1', but when i tried to print the respective character using cout<<char(-1); it just printed a space!?

//I used Dev C++ Ver 5.11 (compiler)

The Mathematical Problem with the Modulus Operator

When negative number is divided by its positive counterpart will give remainder 0;
for eg. cout<<(-5)%(5); //will print 0

BUT, a problem is that it may return negative remainders also, which is mathematically wrong
for eg. cout<(-5)%2; //will print -1
//actually it should have given remainder 1 not -1

NOTE....

C++ with its math.h (or cmath) provides a function called "remainder(x,y)", it corrects this problem as well as it is more advance since it can also give floating point remainders... You may use that IF you think such case/need can be encountered
remainder() requires two arguments () of any arithmetic type