Search code examples
c++classconstructormakefileprogram-entry-point

How can I call a constructor in main() c++?


I have two classes.

fileInfo.cpp:

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

class fileInfo{

private:

string fileName;
string fileType;

public:
/** 
**/
fileInfo(string s){
    fileName = s;
    fileType = "hellooo";

}
string getName() {
    return fileName;
}
};

main.cpp

#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[]){

fileInfo f("test");
std::cout << f.getName();

}

The fileInfo object "f" is not being initialized and I get an error saying that fileInfo is not in scope. I am using a makefile to compile my code which looks like.

all: main.cpp fileInfo.cpp
    g++ main.cpp fileInfo.cpp -o out

Solution

  • Here's the correct way to do it:

    fileInfo.h:

    #include <iostream>
    #include <string>
    #include <fstream>
    using namespace std;
    
    class fileInfo{
    
    private:
    
      string fileName;
      string fileType;
    
    public:
    
      fileInfo(string s);
    
      string getName();
    };
    

    fileInfo.cpp:

    #include "fileInfo.h"
    
    fileInfo::fileInfo(string s){
        fileName = s;
        fileType = "hellooo";
    }
    
    string fileInfo::getName() {
        return fileName;
    }
    

    main.cpp

    #include <iostream>
    #include <string>
    #include "fileInfo.h"
    
    using namespace std;
    int main(int argc, char* argv[]){
    
      fileInfo f("test");
      std::cout << f.getName();
    
    }