Wednesday 2 September 2015

mastering c++ (1)

hi friends in this tutorial we will learn some of the cool stuffs on c++.

first initialization stuffs
..

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<bits/stdc++.h>
#include<complex>
using namespace std;
int main()
{
    double d=2.2;
    int i=7;
    d=d+i;
    i=d*i;
    double ddd{2.3};
    complex<double>z=1;
    complex<double>z2{1,2};
    complex<double>z3={1,2};
    vector<int>v{1,2,3,4,5};
    int id{2};
    auto bd=true;                //a bool
    auto cd='x';                //a char
    auto idd=123;                 //an int
    auto dd=1.2;                 //a double
    auto zd=sqrt(12);             //power type whatever z returns
    cout << i << "\n" << d << "\n" << ddd << "\n" << z << "\n" << z2 << "\n" << z3 << "\n" << v[0] << "\n" << id << "\n" << bd << "\n" << cd << "\n" << idd << "\n" << dd << "\n" << zd << "\n" ;
    return 0;
}





















theory
complex is a class defined in complex.h file it has all the function for executing complex nunmbers such as trignometric,power,exponential,hyperbolic functions...

auto
when u dont know exactly what is the type of the variable u will recieve then use auto ..
as soon as u declare a type auto it searches for its type using "template aurgument dectection" auto keyword just serve the purpose it doesnot necessarily do the task...
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
#include<bits/stdc++.h>
#include<complex>
using namespace std;
auto f()->decltype(1+2)
{
    return sizeof(f);
}
int main()
{
    cout<<f()<<'\n';
    return 0;
}







decltype is use to provide the type to a function here (1+2) was in int so returned value is 4

constants

const ->promises that it will not change the value
constexpr->evaluated at compile time and the value assigned must also be const

to understand look the following the code snippet.

1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include<bits/stdc++.h>
#include<complex>
using namespace std;
int main()
{
    const int d=17;
    int i=2;
    constexpr int l1=d;
    const int w1=d;
    cout<<l1<<'\n'<<w1<<'\n';
    l1=2;
    w1=3; 
    return 0;
}










1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
#include<bits/stdc++.h>
#include<complex>
using namespace std;
int main()
{
    const int d=17;
    int i=2;
    constexpr int l1=d;
    constexpr int l2=i;
    const int w1=d;
    const int w2=i;
    cout<< l1<<'\n'<<l2<<'\n'<<w1<<'\n'<<w2; 
    return 0;
}








notice this error shown in compile time and no error for "const"


1
 2
 3
 4
 5
 6
 7
 8
 9
10
#include<bits/stdc++.h>
#include<complex>
using namespace std;
constexpr double square(double x){return x;}
int main()
{
    cout<<square(2);
    cout<<square(3);
    return 0;
}

here u may confuse that the function is a constexpr but still it is accepting a variable input but the fact is that this function is immutable means u cannot inherit this function nor modify it... something like final keyword in java...

1 comment: