Constructors

Nov 16, 2015 at 9:27pm
Hello!

I am writing a program exactly like this one:
http://www.cplusplus.com/forum/beginner/86236/

I read through the comments and watched the recommended videos, but similar to the original person posting, I am not understanding the constructors... if anyone else has any tips, videos, tutorials on how to correct the code using constructors, please let me know!

Thanks!
Nov 16, 2015 at 9:44pm
Constructors are quite simple. They are simply functions that are called when an object is instantiated (created). A constructor is typically used to initialize that object.

1
2
3
4
5
6
7
8
9
10
11
12
class foo
{  int bar;   // uninitialized variable
public:
    foo ()  // Default constructor
    { bar = 0;  // set bar to an initial value
    }
};

int main ()
{  foo a;  // Create an instance of foo called a.  foo's default constructor is called.
    return 0;
}

Topic archived. No new replies allowed.