Default Arguments defining static member - c++

I m reading The C++ Programming Language 4e. In the part of Default Argument I dont understand below code. I try to compile but there is an error. Anyway what Bjarne trying to explaing? A default argument is type checked at the time of the function declaration and evaluated at the
time of the call. For example:
class X
{
public:
static int def_arg;
void f(int = def_arg);
// ...
};
int X::def_arg = 7;
void g(X& a)
{
a.f(); // maybe f(7)
a.def_arg = 9;
a.f(); // f(9)
}
Error is :
unresolved external symbol "public: void __thiscall X::f(int)" (?f#X##QAEXH#Z) referenced in function "void __cdecl g(class X &)" (?g##YAXAAVX###Z)
MS c++ 2013

You just declared f but need to define the body of f:
void f(int = def_arg);
For example
void X::f(int)
{
// Do something
}
or
class X
{
// ...
void f(int = def_arg)
{
// Do something
}
};
Live code.

Related

pointer to function methods within the class not working

I'm trying to to write a code that will call a function that receive a pointer to other function within the same class, and call get_num method from main.
but when doing include to TestClass.h from main, I'm getting linkage errors
class TestClass{
public:
void get_num(int num);
void foo(int num, void(TestClass::*function)(int));
void boo(int num);
};
void TestClass::boo(int num)
{
std::cout << "number: " << num << std::endl;
}
void TestClass::foo(int num, void(TestClass::*function)(int))
{
(this->*function)(num);
}
void TestClass::get_num(int num)
{
foo(num, &TestClass::boo);
}
Following is the main code:
#include "TestClass.h"
int main()
{
TestClass tc1;
tc1.get_num(5);
system("pause");
return 1;
}
The following errors appears:
1>main.cpp
1>TestClass.obj : error LNK2005: "public: void __thiscall TestClass::boo(int)" (?boo#TestClass##QAEXH#Z) already defined in main.obj
1>TestClass.obj : error LNK2005: "public: void __thiscall TestClass::foo(int,void (__thiscall TestClass::*)(int))" (?foo#TestClass##QAEXHP81#AEXH#Z#Z) already defined in main.obj
1>TestClass.obj : error LNK2005: "public: void __thiscall TestClass::get_num(int)" (?get_num#TestClass##QAEXH#Z) already defined in main.obj
1>c:\Proj4.exe : fatal error LNK1169: one or more multiply defined symbols found
Pointer to a method is not the same as a pointer to a simple function. If you only want to be able to accept a pointer to the method of the same class you can rewrite your method like this:
void TestClass::foo(int num, void(TestClass::*function)(int))
{
(this->*function)(num);
}
void TestClass::get_num(int num)
{
foo(num, &TestClass::boo);
}
This allows foo() to accept a pointer to any method in TestClass but not to any method of any other class nor to a simple function. It also calls the received method on the same object (note: this in this->*function).

Linker can't find a namespace's functions

See code below. There's something wrong with it, because the linker is complaining it can't find the Memory's functions, but I can't figure out why.
memory.h
#pragma once
#include "includes.h" //it just includes other strandard headers.
class MemoryUnit
{
public:
MemoryUnit() {}
virtual int getValue() = 0;
virtual int getSize() = 0;
virtual void setValue(int) = 0;
virtual ~MemoryUnit() {};
};
class Byte : public MemoryUnit
{
int value;
public:
static int size;
Byte(int byte) :value(byte) {};
int getSize() { return size; }
int getValue() { return value; };
void setValue(int byte) { value = byte; }
~Byte() {};
};
namespace Memory
{
extern int size;
extern MemoryUnit** map;
void checkAddress(int address);
int read(int adress);
MemoryUnit* getOperation(int address);
void write(int adress, MemoryUnit* data);
void writeByte(int adress, int data);
}
memory.cpp
#include "includes.h"
#include "memory.h"
#include "simulator.h" // it contains only externed constants.
namespace Memory
{
int size = 0;
MemoryUnit** map = NULL;
inline MemoryUnit* getOperation(int address)
{
return map[address];
}
inline void checkAddress(int address)
{
if (address < 0 || address >= MAX_MEMORY_SIZE)
throw std::out_of_range("Invalid memory address.");
}
inline int read(int address)
{
checkAddress(address);
return map[address]->getValue();
}
inline void write(int address, MemoryUnit* data)
{
checkAddress(address);
delete map[address];
map[address] = data;
}
inline void writeByte(int address, int data)
{
checkAddress(address);
map[address]->setValue(data);
}
}
Everywhere the class/namespace memory.h declares is includes memory.h. Is here anything wrong in the code below?
Edit:
I'm using Visual Studio 2015.
Errors I got when building the project:
LNK1120 5 unresolved externals simulator.exe
LNK2019 unresolved external symbol "void __cdecl Memory::writeByte(int,int)" referenced in function "void __cdecl ALU::setFlags(int)" alu.obj
LNK2001 unresolved external symbol "void __cdecl Memory::writeByte(int,int)" cu.obj
LNK2019 unresolved external symbol "class MemoryUnit * __cdecl Memory::getOperation(int)" referenced in function "void __cdecl CU::run(void)" cu.obj
LNK2001 unresolved external symbol "void __cdecl Memory::writeByte(int,int)" helpers.obj
LNK2019 unresolved external symbol "void __cdecl Memory::write(int,class MemoryUnit *)" referenced in function "void __cdecl readProgramCommands(void)" helpers.obj
LNK2001 unresolved external symbol "public: virtual int __thiscall MemoryPointer::getValue(void)" helpers.obj
LNK2001 unresolved external symbol "public: virtual int __thiscall IndirectMemoryPointer::getAddress(void)" helpers.obj
LNK2001 unresolved external symbol "void __cdecl Memory::writeByte(int,int)" main.obj
alu.h and alu.cpp for the first error:
//alu.h
#pragma once
#include "includes.h"
#include "operation.h"
namespace ALU
{
int operation(Operation* op);
void setFlags(int result);
}
//alu.cpp
#include "includes.h"
#include "simulator.h"
#include "alu.h"
#include "memory.h"
#include "operation.h"
namespace ALU
{
int operation(Operation* operation)
{
// ...
setFlags(result);
return result;
}
inline void setFlags(int result)
{
Memory::writeByte(FLAG_Z, result == 0);
// ...
}
}
You need to put the inline function definition inside your header file (they both must appear in every translation unit where they are used), you can separate declaration and definition but both must be in the header file. Also they must be declared as inline.
N4140 dcl.fct.spec 7.1.2.4
An inline function shall be defined in every translation unit in which it is odr-used and shall have exactly
the same definition in every case (3.2). [ Note: A call to the inline function may be encountered before its
definition appears in the translation unit. —end note ] If the definition of a function appears in a translation
unit before its first declaration as inline, the program is ill-formed.
When you're using inline functions or methods, their definitions should be visible for every source unit that uses them. You defined your inline functions in Memory.cpp, that's why you get 'unresolved' linker error.
To fix your problem you can:
Remove inline modifier and keep functions definitions in Memory.cpp.
Keep inline modifier but move functions definitions to Memory.h.

Unresolved external symbol "public: int myclass::get_a (void)" How do I resolve this code? Noobie Q

Noobie programmer here learning C++ for the first time. The following is excerpted code from Teach Yourself C++ 3rd Edition.
I'm dying help me, I'm learning about classes, but I can't get this code to compile on visual studio or on Code::Blocks. :(
//#include "stdafx.h"
#include <iostream>
//I understand this. Headers, etc.
using namespace std;
//and this, name traffic management system
class myclass {
//private to myclass
int a;
public:
void set_a(int num);
int get_a();
};
/*I understand int a is private/inaccessible from the rest of the code
and void set_a(int num) is the dummy function.*/
void myclass::set_a(int num)
//not sure what this is
{
a = num;
}
/*self explanatory*/
int _tmain(int argc, _TCHAR* argv[])
{
myclass ob1, ob2;
ob1.set_a(10);
ob2.set_a(99);
cout << ob1.get_a() << "\n";
cout << ob2.get_a() << "\n";
return -5;
}
/*This is just supposed to output the number 10 and 99 right?? So why isn't it?*/
On Visual Studio the full error description is:
Error 1 error LNK2019: unresolved external symbol "public: int __thiscall myclass::get_a(void)" (?get_a#myclass##QAEHXZ) referenced in function _wmain c:\Users\bernardo pliego\documents\visual studio 2013\Projects\Chapter 1.5\Chapter 1.5\Chapter 1.5.obj Chapter 1.5
On Code::Blocks I receive the following error:
In function 'main':
undefined reference to 'my_class::get_a()'
I am in dire need of help, can someone explain this to me?
Because you don't define get_a, you only declare it. Add a definition like this:
int myclass::get_a() { return a; }
Or just define it inline:
class myclass {
//private to myclass
int a;
public:
void set_a(int num);
int get_a() { return a };
};
You don't ever define int get_a(); so you get an error at link-time.
Include this just above your (rather hubristic) /*self explanatory*/ comment
int myclass::get_a()
{
return a;
}

Passing 2D array into function

I'd like to pass my 2D Array of class Menza into function..
class Menza
{
public:
string PrintLunch() const {return Lunch;};
unsigned int PrintID() const {return ID;};
double PrintPrice() const {return Price;};
double PrinteValue() const {return eValue;};
string PrintDescription() const {return Description;};
void ChangeLunch(string Change) {Lunch = Change;};
void ChangePrice(double Change) {Price = Change;};
void ChangeID(int Change) {ID = Change;};
void ChangeeValue(double Change) {eValue = Change;};
void ChangeDescription(string Change) {Description = Change;};
private:
string Lunch;
double Price;
unsigned int ID;
string Description;
double eValue;
};
const int Lunches = 5;
void LoadFile(bool FileChoice,Menza (*InputFromFile)[Lunches]);
void CustomerSelection(Menza CustomerSelect[],Menza (*InputFromFile)[Lunches]);
int main()
{
Menza InputFromFile[Lunches][Lunches];
Menza CustomerSelect[Lunches];
bool FileChoice = false;
LoadFile(FileChoice,InputFromFile);
CustomerSelection(CustomerSelect,InputFromFile);
}
Once I compile this, it shows me:
Semestralka.obj : error LNK2019: unresolved external symbol "void __cdecl LoadFile(bool,class Menza (*)[5])" (?LoadFile##YAX_NPAY04VMenza###Z) referenced in function _main
1>E:\My VSB\ZP projekty\Semestralka\Debug\Semestralka.exe : fatal error LNK1120: 1 unresolved externals
Can someone explain me whats wrong in this function call?
Thanks
You don't have definition of LoadFile function, only declaration. Therefore compiler have no way to understand what this function should do.
You must define it or link a library where it is defined (and include a header from this library). (Same is true for CustomerSelection too).
Read more about difference between definition and declaration here: declare_vs_define

Multiple class in a list c++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Why can templates only be implemented in the header file?
Main class
int main() {
initCarList();
}
void initCarList() {
List<Car> carList;
Car c1 = Car("Toyota", "Bettle", 5);
carList.add(c1);
Car c2 = Car("Mercedes", "Bettle", 7);
carList.add(c2);
Car c3 = Car("FireTruck", "Large Van", 20);
carList.add(c3);
Car c4 = Car("Puma", "Saloon Car", 10);
carList.add(c4);
}
List class
#include "List.h"
#include <iostream>
using namespace std;
template <typename ItemType>
class List {
private:
ItemType itemList[10];
int size;
public:
List();
void add(ItemType);
void del(int index);
bool isEmpty();
ItemType get(int);
int length();
};
template<typename ItemType>
List<ItemType>::List() {
size = 0;
}
template<typename ItemType>
void List<ItemType>::add(ItemType item) {
if(size < MAX_SIZE) {
itemList[size] = item;
size++;
} else {
cout << typename << " list is full.\n";
}
}
I got errors like these
Error 3 error LNK2019: unresolved external symbol "public: void
__thiscall List::add(class Car)" (?add#?$List#VCar####QAEXVCar###Z) referenced in function "void
__cdecl initCarList(void)" (?initCarList##YAXXZ) C:\Users\USER\Desktop\New
folder\DSA_Assignment\main.obj DSA_Assignment
Did I do anything wrongly in my code? NEED HELP THANKS!
There is a syntax error (cout << typename ) in your code. I don't know how you got the linker error. May be its not being compiled at all.
otherwise its okay http://ideone.com/PGWGZu
Clearly you did as it doesn't work! Flippancy aside, let's take a look at the error message bit by bit:
Error 3 error LNK2019: unresolved external symbol
So this is a linkage error. The linker is trying to put together the units that were individually compiled together, but in this case it can't find an external symbol - usually a function or variable name.
"public: void __thiscall List::add(class Worker)" (?add#?$List#VWorker####QAEXVWorker###Z)
This is the full signature of the function that you're missing. It's name manged unfortunately but with your context knowledge of the code that you're writing, you should be able to tell that it's:
void List::add(Worker)
The next bit ...
referenced in function "void __cdecl initWorkerList(void)" (?initWorkerList##YAXXZ) C:\Users\USER\Desktop\New folder\DSA_Assignment\main.obj DSA_Assignment
... is telling you where the problem is happening, i.e where in the code it's trying to link, there is a reference to the missing function. Again, after demangling it's in:
void initWorkerList()
As you can see, with a bit of graft, you can determine exactly what you've done wrong here. Hope this helps.