I have two files:
File1.cpp
File2.cpp
File1 is my main class which has the main method, File2.cpp has a class call ClassTwo and I want to create an object of ClassTwo in my File1.cpp
I compile them together by
g++ -o myfile File1.cpp File2.cpp
but when I try to create by
//create class two object
ClassTwo ctwo;
It doesn’t work.
Error was
ClassTwo was not declared in this scope.
This is my main.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
//here compile error - undeclare ClassTwo in scope.
ClassTwo ctwo;
//some codes
}
Here is my File2.cpp
#include <iostream>
#include <string>
using namespace std;
class ClassTwo
{
private:
string myType;
public:
void setType(string);
string getType();
};
void ClassTwo::setType(string sType)
{
myType = sType;
}
void ClassTwo::getType(float fVal)
{
return myType;
}
Got respond of splitting my File2.cpp into another .h file but if i am declaring a class, how do i split it into another .h file as i need to maintain the public and private of the variable(private) and functions(public) and how do i get ClassTwo ctwo to my File1.cpp at main method
Your code needs to be separated out in to interfaces(.h) and Implementations(.cpp).
The compiler needs to see the composition of a type when you write something like
This is because the compiler needs to reserve enough memory for object of type
ClassTwoto do so it needs to see the definition ofClassTwo. The most common way to do this in C++ is to split your code in to header files and source files.The class definitions go in the header file while the implementation of the class goes in to source files. This way one can easily include header files in to other source files which need to see the definition of class who’s object they create.
You cannot simple put all the code in source file and then include that source file in other files.C++ standard mandates that you can declare a entity as many times as you need but you can define it only once(One Definition Rule(ODR)). Including the source file would violate the ODR because a copy of the entity is created in every translation unit where the file is included.
Your code should be organized as follows:
//File1.h
//File2.h
//File1.cpp
//File2.cpp
//main.cpp
If your code only needs to create pointers and not actual objects you might as well use Forward Declarations but note that using forward declarations adds some restrictions on how that type can be used because compiler sees that type as an Incomplete type.