Let me start by stating that you need to review some C++ tutorials or else you're going to drive yourself (and others) crazy asking such basic questions on these forums. That said, there are two common ways of initializing class member variables, using 1) The constructor initializer list or; 2) by assigning values in your constructor.
Consider this Example.h class definition:
// Example.h
class Example
{
public:
Example();
~Example();
private:
int a;
int b;
}
// Example.h
class Example
{
public:
Example();
~Example();
private:
int a;
int b;
}
To copy to clipboard, switch view to plain text mode
Then if you wanted to initialize the class member variables via the constructor initializer list, you would:
// Example.cpp
Example::Example()
: a(0)
, b(0)
{
}
Example::~Example()
{
}
// Example.cpp
Example::Example()
: a(0)
, b(0)
{
}
Example::~Example()
{
}
To copy to clipboard, switch view to plain text mode
If you wanted to initialze the same member variables via assignment in the construtor, you would do:
// Example.cpp
Example::Example()
{
a = 0;
b = 0;
}
Example::~Example()
{
}
// Example.cpp
Example::Example()
{
a = 0;
b = 0;
}
Example::~Example()
{
}
To copy to clipboard, switch view to plain text mode
Originally Posted by
T1001
Okay, so I've successfully made a constructor in the main.cpp and seems to be working fine except for two of the inline functions:
// by the fxs
Ships::Ships() {
int x = barge; int solution = 1200;
int destroyer_1 = destroyer; int submarine_1 = submarine;
int aircraft_carrier_1 = aircraft_carrier;
//mult (int a, int b){solution = a * b;};
//add (int c, int d){solution = c + d; };
int barge_1 = barge;
int product_s = 0;
// TODO Auto-generated constructor stub
}
Ships::Ships() {
int x = barge; int solution = 1200;
int destroyer_1 = destroyer; int submarine_1 = submarine;
int aircraft_carrier_1 = aircraft_carrier;
//mult (int a, int b){solution = a * b;};
//add (int c, int d){solution = c + d; };
int barge_1 = barge;
int product_s = 0;
// TODO Auto-generated constructor stub
}
To copy to clipboard, switch view to plain text mode
Those variables you define and initialize in lines 4-10 of your constructor are not class member variables, they're local variables created on the stack that disappear when your constructor has been executed. Class member variables must be defined as such and are defined in the class definition. See above for the Example class definition in Example.h. The two variables a and b are integer variables that are declared as private member variables.
Added after 9 minutes:
Originally Posted by
T1001
I've looked all over the internet but can't find what I need.
Of course that's a crazy statement. Google "c++ class construction" or "c++ class design". Pretty sure there are a few million hits at least.
Bookmarks