I recently switched to C++ from JAVA. I am trying to implement Factory Design Pattern.
Here are my files.
Shape.h
#pragma once
class Ishape
{
public:
virtual void draw()=0;
};
Rectangle.h
#pragma once
#include"Shape.h"
class Rectangle :public Ishape
{
public:
void draw();
};
Rectangle.cpp
#include"Rectangle.h"
#include<iostream>
void draw()
{
std::cout << "Rectangle Draw" << std::endl;
}
Square.h
#pragma once
#include"Shape.h"
class Square :public Ishape
{
public:
void draw();
};
Square.cpp
#include"Square.h"
#include<iostream>
void draw()
{
std::cout << "Square Draw" << std::endl;
}
ShapeFactory.h
#pragma once
#include "Shape.h"
#include<iostream>
class ShapeFactory
{
public:
static Ishape* getShape(std::string type);
};
ShapeFactory.cpp
#include"ShapeFactory.h"
#include"Rectangle.h"
#include"Square.h"
static Ishape* getShape(std::string type)
{
Ishape* s = nullptr;
if (type == "Rectangle")
{
s= new Rectangle;
}
else if (type == "Square")
{
s= new Square;
}
return s;
}
Client Code:
Source.cpp
#include<iostream>
#include"ShapeFactory.h"
int main()
{
using namespace std;
Ishape* shape = ShapeFactory::getShape("Rectangle");
shape->draw();
return 0;
}
When I run this,I got the following Run-Time Errors:
Severity Code Description Project File Line Suppression State
Error LNK2005 "void __cdecl draw(void)" (?draw@@YAXXZ) already defined in Rectangle.obj 1
Error LNK2019 unresolved external symbol "public: static class Ishape * __cdecl ShapeFactory::getShape(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?getShape@ShapeFactory@@SAPAVIshape@@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) referenced in function _main Project1 C:\Users\nikhil\source\repos\Project1\Project1\Source.obj 1
Error LNK1120 1 unresolved externals Project1 C:\Users\nikhil\source\repos\Project1\Debug\Project1.exe 1
Few Points: I read that It is good practice to keep separate header files and code files,that is why I followed that.
I followed this example of Factory Design Pattern.(https://www.tutorialspoint.com/design_pattern/factory_pattern.htm)
Can anyone please suggest,how to overcome the error.Any other tips from c++ point will also be helpful.