Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we declare constructor before member variables?

Can the constructer declared before the member variable alter its value?

I thought only the code below works,

struct test {
    int a; 
    test(int t): a(t) {}
};

but I found the code below also works.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct test {
    test(int t): a(t) {}
    int a; 
};

Usually, in function, we cannot use the variable that is not declared. Why the code above is OK?

>Solution :

Actually in C++ there’s an exception that there’s no need for forward declaration of functions and variable of a class/struct.

You can see my such examples on the internet like this:

class foo
{
public:
    foo(int x) : my_var(x) {}
private:
    int my_var;
};

The above is 100% valid.

You can also call a function of a class before it is defined like:

class bar
{
public:
    bar() 
    {
        this->my_below_func();
    }

    int my_below_func()
    {
        return 1;
    }
};

Always remember that these tricks aren’t going to work outside C++ classes/structs, you will need forward declaration of your functions and variables.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading