Tim Tim - 3 months ago 9
C++ Question

Trynig to figure out why my Member Initializer list doesnt work

#include<iostream>
using namespace std;
class a
{
public:
a():a2(1),
b2(2),
c2(3)
{
cout <<"waruup\n";
}
~a()
{
cout<<"Its over brah\n";
}


void kappa()
{
cout << a2 <<endl;
}

void kappa1()
{
cout << b2 <<endl;
}

void kappa2()
{
cout << c2 <<endl;
}
};

main ()
{
a ao;
a *lol=&ao;
//ao.kappa();
lol->kappa();
lol->kappa1();
lol->kappa2();

}


why doesnt it run? I get an error at a():a2(1),
Am i getting soemething wrong? Isnt it suppose to make a2=1 and then print 1 when void kappa is called.Iam fairly new to programming and C++ in specific so excuse my nooby mistakes.

Answer

You must declare the fields a2, b2 and c2 to initialize and use them.

#include<iostream>
using namespace std;
class a
{
    // declaretion of fields
    int a2, b2, c2;

    public:
        a():a2(1),
            b2(2),
            c2(3)
        {
            cout <<"waruup\n";
        }
        ~a()
        {
            cout<<"Its over brah\n";
        }


        void kappa()
        {
            cout << a2 <<endl;
        }

        void kappa1()
        {
            cout << b2 <<endl;
        }

        void kappa2()
        {
            cout << c2 <<endl;
        }
};

// don't omit the return type of functions
int main ()
{
    a ao;
    a *lol=&ao;
    //ao.kappa();
    lol->kappa();
    lol->kappa1();
    lol->kappa2();

}

Also note that you mustn't omit return types of functions in C++.