Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning value for a class variable

Tags:

c++

There are some codes as follows:

class A{
    private :
        int a, b;
    public :
        A(int x):a(x),b(a*a){}
    int getA(){
        return a;
    }
    int getB(){
       return b;
    }
};

int main(){
    A a=13;
    printf("%d %d\n", a.getA(), a.getB() );
    return 0;
}

The line A a=13, I can't understand how it call the constructor and why? I think there have't any definition about the cast and won't get compiled, but it runs well and called the constructor function.

like image 467
SparkFour Avatar asked Jul 22 '26 06:07

SparkFour


1 Answers

This is called an implicit declaration. When you write A a=13;, your compiler is smart enough to recognize that what you really mean is A a(13); since you have declared a constructor that takes an int as an argument. If you don't want this to happen, put an explicit keyword before your constructor, and then you will get compiler errors unless you write A a(13); instead of A a=13;.

like image 79
wolfPack88 Avatar answered Jul 23 '26 22:07

wolfPack88



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!