THE POST BELOW IS MORE THAN 5 YEARS OLD. RELATED SUPPORT INFORMATION MIGHT BE OUTDATED OR DEPRECATED
On 11/04/2012 at 11:44, xxxxxxxx wrote:
This is a generic C++ question. Not related to the SDK.
I'm trying to force myself to stop putting everything in one file(a bad habit picked up from scripting). And learn how to construct OOP style programs. And I'm having a hard time with the constructors.
I'm trying to use only declarations in my .h files. And not do any implementations in them at all. But I can't get my constructors to work that way.
If I implement the constructor variables in the .h file it works. But it does not work when implemented in the .cpp file. And I don't know why this is happening.
Example:
.h file
#pragma once
#include<iostream>
#include<string>
using namespace std;
class Name
{
public:
string fname;
//Name(string name); //<--This is how I want to declare it
Name(string name)
{
fname = name; //This works..But I don't want to implement any code like this in the .h file!!
}
string toString(); //Declare a method to return the string value in the constructor..This is fine
};
..............
.cpp file
#include "name.h"
//This is how/where I want to implement the code..
//But it won't work this way...It returns a blank line
//Name::Name(string name)
//{
// string fname = name; //<--Why won't this code work here in the .cpp file?
//}
string Name::toString()
{
return fname; //This works fine being implemented from inside of the .cpp file
}
................
main.cpp file
#include<iostream>
#include<string>
#include "name.h"
using namespace std;
int main ()
{
Name myname("Scott");
cout<< myname.toString() <<endl; //prints the name "Scott" from the constructor's parameter
system ("pause"); // wait for user to close the output window
return 0;
}
Can anyone tell me how to correctly write the code in the .cpp file so it works from there. Instead of implementing the code in the .h file?
I want to only declare the constructor in the .h file. And then let the .cpp file do the implementation(the work).
-ScottA