0
votes

Suppose I have 2 header file called Computer.h and Software.h both are implemented on separated file Computer.cpp and Software.cpp, my concern is to declare a Software in a Computer.

Computer.h

#ifndef _COMPUTER_H
#define _COMPUTER_H
#include "Software.h"

class Computer{
    private:
        std::string computerName;
        int ramSize;
        Software computerSoftware;

    public:
        Computer();
        Computer(std::string name, int size);
        int GetRamSize();
        std::string GetComputerName();
};

#endif

Software.h

#ifndef _SOFTWARE_H
#define _SOFTWARE_H

class Software{
    private:
        std::string softwareName;
        double softwarePrice;
    public:
        Software();
        Software(std::string name, double price);
        double GetPrice();
        std::string GetSoftwareName();
};

#endif

Computer.cpp

#include <string>
#include <iostream>
#include "Computer.h"

using namespace std;

Computer::Computer(string name, int size){
    computerName = name;
    ramSize = size;
}

int Computer::GetRamSize(){
    return ramSize;
}

string Computer::GetComputerName(){
    return computerName;
}

Software.cpp

#include <string>
#include <iostream>
#include "Software.h"

using namespace std;

Software::Software(string name, double price){
    softwareName = name;
    softwarePrice = price;
}

double Software::GetPrice(){
    return softwarePrice;
}

string Software::GetSoftwareName(){
    return softwareName;
}

However it deliver to build error on my visual c++ 2010 express:

Computer.obj : error LNK2019: unresolved external symbol "public: __thiscall Software::Software(void)" (??0Software@@QAE@XZ) referenced in function "public: __thiscall Computer::Computer(class std::basic_string,class std::allocator >,int)" (??0Computer@@QAE@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H@Z) 1>C:\Users\farissyariati\documents\visual studio

2010\Projects\CppConsoleApps\Debug\CppConsoleApps.exe : fatal error LNK1120: 1 unresolved externals

1
You forgot to implement Software::Software().R Sahu
Where should I add it? I add it on Software.cpp as a constructor and it still failed on build.farissyariati

1 Answers

0
votes

This function

Computer::Computer(string name, int size){
    computerName = name;
    ramSize = size;
}

is equivalent to:

Computer::Computer(string name, int size) : computerName(), computerSoftware() {
    computerName = name;
    ramSize = size;
}

computerName and computerSoftware are initialized using default constructors. Since you did not implement the default constructor of Software, you are experiencing the linker error.

Implement Software::Software() in Software.cpp and everything should work.

Software::Software() : softwareName(), softwarePrice(0.0) {
}