I am a former c programmer and have spent the last few years working in python. I am now attempting to understand c++ object programming. I have created a class which contains a structure. I would like to pass a reference to the class to a function. I have read several articles about passing by reference like the following:
passing object by reference in C++
Is it possible to pass a class reference to a function or is this something that can't be done in c++?
I am attempting to pass a reference to a class to a print printStruct function. Here is my example:
CORRECTED CODE
#include "stdafx.h"
#include <string>
#include <iostream>
class SampleClass
{
public:
struct TestStructType {
std::string string1;
};
SampleClass();
std::string GetString1();
private:
TestStructType PrivateVar;
};
SampleClass::SampleClass()
{
PrivateVar.string1 = "String 1";
};
std::string SampleClass::GetString1() { return PrivateVar.string1; };
void printStruct(SampleClass&);
int _tmain(int argc, _TCHAR* argv[])
{
SampleClass sc;
std::cout << sc.GetString1() << std::endl;
printStruct(sc);
return 0;
};
void printStruct(SampleClass& ssc)
{
std::cout << "The String is: " << ssc.GetString1() << std::endl;
};
Error messages: Error 1 error C4430: missing type specifier - int assumed. Note: C++ does not support default-int c:\users\visual studio 2013\projects\pass class\pass class\pass class.cpp 8 1 Pass Class
Error 2 error C2143: syntax error : missing ',' before '&' c:\users\visual studio 2013\projects\pass class\pass class\pass class.cpp 8 1 Pass Class
5 IntelliSense: the object has type qualifiers that are not compatible with the member function object type is: const SampleClass c:\Users\Visual Studio 2013\Projects\Pass Class\Pass Class\Pass Class.cpp 41 37 Pass Class