Reputation: 3431
I'm new to C++ and I'm trying to make a program to do conversions between two objects. I have Class1
, Class2
and Convert
. I want a function that takes in a Class1 object, converts it to a Class2 object and returns the Class2 object. Right now my convert class is basically:
Convert.h
#ifndef Convert_H
#define Convert_H
#include "Class1.h"
#include "Class2.h"
class Convert
{
public:
Convert();
Class1 c1;
Class2 c2;
Class2 C1ToC2(Class1);
};
#endif // Convert_H
Convert.cpp
#include "Convert.h""
#include "Class1.h"
#include "Class2.h"
Convert::Convert()
Class2 Convert::C1ToC2(Class1 c1)
{
//conversions
return c2;
}
I have a few questions about this. I don't want to have the convert functions in the other classes which is why I created a separate class.
Once again I am new to C++, I do have a few books that I'm trying to learn from but they don't really tell how to use objects like this so I apologize if this is a stupid question and I'm doing it completely wrong.
Upvotes: 1
Views: 75
Reputation: 56863
In C++, you can simply use a function directly, you don't need a class Convert
.
In Convert.h
:
#ifndef Convert_H
#define Convert_H
#include "Class1.h"
#include "Class2.h"
// declare the function
Class2 convert( const Class1& input );
#endif
and in Convert.cpp
:
#include "Convert.h"
// define the function
Class2 convert( const Class1& input )
{
Class2 result;
// do conversion
return result;
}
Note that this is just the basics, it can be improved in several aspects but it should help you to get started and experiment on your own.
Upvotes: 3
Reputation: 121
With regards to your second question, the reason the code doesn't compile is because you forgot the curly braces after Convert::Convert()
. (Or maybe a semicolon. But I assume you wanted to define the ctor)
Upvotes: 1