Initializing object of a class inside another class - c++

I have a class MySeqBuildBlockModule that I am inheriting from: public SeqBuildBlock.
Other than constructor and destructor, this class MySeqBuildBlockModule has a method: prep.
class MySeqBuildBlockModule: public SeqBuildBlock
{
friend class SeqBuildBlockIRns;
public:
MySeqBuildBlockModule (SBBList* pSBBList0, long TI1_In, long TI2_In) // more arguements in this constructor of derived class
: SeqBuildBlock (pSBBList0)
{
TI1 = TI1_In; //in us
TI2 = TI2_In; //in us
pSBBList2 = pSBBList0;
//SeqBuildBlockIRns myIRns_3(pSBBList2); //Defined in libSBB.h
}
//~MySeqBuildBlockModule(){}
virtual bool prep (MrProt* pMrProt, SeqLim* pSeqLim, SeqExpo* pSeqExpo);
virtual bool run (MrProt* pMrProt, SeqLim* pSeqLim, SeqExpo* pSeqExpo, sSLICE_POS* pSLC);
protected:
private:
long TI1; //in us
long TI2; //in us
SBBList* pSBBList2;
SeqBuildBlockIRns myIRns_3(pSBBList2); // Line 106
};
bool MySeqBuildBlockModule::prep(MrProt* pMrProt, SeqLim* pSeqLim, SeqExpo* pSeqExpo)
{
NLS_STATUS lStatus;
double dEnergyAllSBBs_DK = myIRns_3.getEnergyPerRequest(); //Line 113
// Now we prepare:
lStatus = pSBBList->prepSBBAll(pMrProt, pSeqLim, pSeqExpo, &dEnergyAllSBBs_DK); // Line 116
if (lStatus ) {
cout << "DK: An error has occurred while preparing SBBs"<< endl;
}
return lStatus;
}
I would have like to intiantiate an object "myIRns_3" of a class defined in third party library
SeqBuildBlockIRns myIRns_3(pSBBList2);
and would like to access it from the prep function as:
double dEnergyAllSBBs_DK = myIRns_3.getEnergyPerRequest();
I tried to instantiate following in either private section or in constructor; but w/o any success:
SeqBuildBlockIRns myIRns_3(pSBBList2);
ERRORS encountered:
When I tried to do it inside the constructor, I get the following errors:
MySBBModule.h(113) : error C2065: 'myIRns_3' : undeclared identifier
MySBBModule.h(113) : error C2228: left of '.getEnergyPerRequest' must have class/struct/union type
MySBBModule.h(116) : error C2065: 'pSBBList' : undeclared identifier
MySBBModule.h(116) : error C2227: left of '->prepSBBAll' must point to class/struct/union
When I tried to do it in private section, I get the following errors:
MySBBModule.h(106) : error C2061: syntax error : identifier 'pSBBList2'
MySBBModule.h(113) : error C2228: left of '.getEnergyPerRequest' must have class/struct/union type
MySBBModule.h(116) : error C2065: 'pSBBList' : undeclared identifier
MySBBModule.h(116) : error C2227: left of '->prepSBBAll' must point to class/struct/union
PS: I have marked the line no in the code that I am posting.
Any help would be appreciated.
Regards,
DK

Your problem is that the below is declaring a function:
SeqBuildBlockIRns myIRns_3(pSBBList2);
What you want to do is declare a member:
SeqBuildBlockIRns myIRns_3;
And then in your constructor construct it with the argument pSBBList2:
MySeqBuildBlockModule (SBBList* pSBBList0, long TI1_In, long TI2_In) // more arguements in this constructor of derived class
: SeqBuildBlock (pSBBList0),
myIRns_3(pSBBList2) // <- construct
{ }

Related

Passing unique pointer child as a reference

VulkanSurface.h:
#include "VulkanInstance.h"
class VulkanSurface {
public:
//Only constructor
VulkanSurface(VulkanInstance &instance); //line 14
};
VulkanSurface.cpp:
VulkanSurface::VulkanSurface(VulkanInstance &instance) {
//...
}
VulkanInstance.cpp:
VulkanInstance::VulkanInstance(const std::vector<const char*> validationLayers) :
validationLayers(validationLayers) {
...
}
main.cpp:
instance = std::make_unique<VulkanInstance>(validationLayers);
surface = std::make_unique<VulkanSurface>(*instance); //line 104
This shows no errors in VisualStudio in form of red squiggly line, but the compilation fails with the following:
1>main.cpp
1>c:\users\karlovsky120\source\repos\vulkanproject\vulkanproject\vulkansurface.h(14): error C2061: syntax error: identifier 'VulkanInstance'
1>c:\users\karlovsky120\source\repos\vulkanproject\vulkanproject\main.cpp(104): error C2440: '<function-style-cast>': cannot convert from 'initializer list' to 'VulkanSurface'
1>c:\users\karlovsky120\source\repos\vulkanproject\vulkanproject\main.cpp(104): note: No constructor could take the source type, or constructor overload resolution was ambiguous
1>c:\users\karlovsky120\source\repos\vulkanproject\vulkanproject\main.cpp(104): error C2672: 'std::make_unique': no matching overloaded function found
1>VulkanInstance.cpp
1>c:\users\karlovsky120\source\repos\vulkanproject\vulkanproject\vulkansurface.h(14): error C2061: syntax error: identifier 'VulkanInstance'

c++ interfaces error; identifier "class" is undefined

Using: VS2010 : New Project -> Windows32 Console App -> Empty Project
Language: C++
Problem: I'm attempting a simple interface test with two classes that implement the interface through the 1 virtual method. I also attempt to use constructors within those two classes to set default values. The main problem occurs when attempting to create an object of either class; the IDE complains the identifier "class" is undefined.
I have checked tens of other posts with the same error but most of them are errors in instantiation(proper term?) where they use
Class obj();
instead of
Class obj;
another issue in the other threads was that the header files were not included in main.cpp AND the concrete class(proper term?). Still other issues involved the ordering of includes(base class should be first), or even improper use of constructors/deconstructors.
I have checked over those issues to see if they would work for me but have been unable to figure out what the problem is.
Any insight would be appreciated!
Error: (all in main.cpp)
Error 1 error C2065: 'Human' : undeclared identifier 6 1 interfaceGameTest
Error 2 error C2146: syntax error : missing ';' before identifier 'hum1' 6 1 interfaceGameTest
Error 3 error C2065: 'hum1' : undeclared identifier 6 1 interfaceGameTest
Error 4 error C2065: 'Orc' : undeclared identifier 7 1 interfaceGameTest
Error 5 error C2146: syntax error : missing ';' before identifier 'orc1' 7 1 interfaceGameTest
Error 6 error C2065: 'orc1' : undeclared identifier 7 1 interfaceGameTest
Error 7 error C2065: 'hum1' : undeclared identifier 10 1 interfaceGameTest
Error 8 error C2227: left of '->getHP' must point to class/struct/union/generic type 10 1 interfaceGameTest
Code:
IPc.h
#ifndef IPC_H_HAS_BEEN_INCLUDED
#define IPC_H_HAS_BEEN_INCLUDED
class IPc {
private:
int hp;
int mana;
int endurance;
public:
void setHP(int h) { hp = h; }
void setMP(int m) { mana = m; }
void setEnd(int e) { endurance = e; }
int getHP() { return hp; }
int getMP() { return mana; }
int getEnd() { return endurance; }
virtual int Attack() = 0;
};
#endif
IPc.cpp
#include "IPc.h"
class Human: public IPc
{
public:
Human::Human()
{
this->setHP(10);
this->setMP(5);
this->setEnd(10);
}
Human::~Human(){}
int IPc::Attack() // I have tried just "int Attack()" as well
{
return 1;
}
};
class Orc: public IPc
{
public:
Orc::Orc()
{
this->setHP(20);
this->setMP(0);
this->setEnd(20);
}
Orc::~Orc() {}
int IPc::Attack()
{
return 5;
}
};
main.cpp
#include <iostream>
#include "IPc.h"
int main()
{
Human hum1; // error Human undefined
Orc orc1; // error Orc undefined
int humHP = 0;
humHP = hum1->getHP();
std::cout << "Human HP is: " << humHP << std::endl;
return 0;
}
Edit
I placed
class Human: public IPc { virtual int Attack() };
inside IPc.h (after the base class) and before #endif(also did one for Orc). I also changed
humHP = hum1->getHP();
to
humHP = hum1.getHP();
Which seems to have cleared up the previous issues(Thanks Mat and Rahul). I am now getting a 'class' type redefinition error. I believe this has to do with the include guards. Do I need to surround each individual class with its own set of guards in the .h file or have I implemented them improperly perhaps?
Edit2
I placed both class declarations in their own header files with their own guards. This seems to have resolved the issue of " 'class' type redefinition". Though there is now an error of unresolved external symbol on the virtual attack calls for both derived classes.
You are not allowed to use qualified names in class member declarations. I.e. when declaring the constructor of class Human inside class Human, you are not allowed to call it Human::Human(). It should be just Human(). The same applies to all other methods.
Trying to declare method int IPc::Attack() inside other classes makes no sense at all. It should be just int Attack().
You declared classes Human and Orc inside IPc.cpp. These classes are only visible inside IPc.cpp and nowhere else. In C++ language class declarations for program-wide classes are typically placed in header files, just how you did it with IPc class.

Using member function of Class in a Vector [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
EDIT: You need to make a vector like this:
vector myVector(5);
not like this:
vector myVector[5];
Instead of vector<team> players[5]; vector<team> players(5); has to be. With this operation you'll create a vector of 5 players. In your code 5 empty vectors are created.
You should get a lot more errors, actually. I get the following:
cl /nologo /EHsc /Za /W4 stackoverflow.cpp
stackoverflow.cpp
stackoverflow.cpp(5) : error C2146: syntax error : missing ';' before identifier 'name'
stackoverflow.cpp(5) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
stackoverflow.cpp(9) : error C2061: syntax error : identifier 'string'
stackoverflow.cpp(10) : error C2146: syntax error : missing ';' before identifier 'getName'
stackoverflow.cpp(10) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
stackoverflow.cpp(10) : warning C4183: 'getName': missing return type; assumed to be a member function returning 'int'
stackoverflow.cpp(22) : error C2511: 'void team::setName(std::string)' : overloaded member function not found in 'team'
stackoverflow.cpp(3) : see declaration of 'team'
stackoverflow.cpp(23) : error C2065: 'name' : undeclared identifier
stackoverflow.cpp(23) : error C2065: 'b' : undeclared identifier
stackoverflow.cpp(30) : error C2556: 'std::string team::getName(void)' : overloaded function differs only by return type from 'int team::getName(void
stackoverflow.cpp(10) : see declaration of 'team::getName'
stackoverflow.cpp(30) : error C2371: 'team::getName' : redefinition; different basic types
stackoverflow.cpp(10) : see declaration of 'team::getName'
stackoverflow.cpp(31) : error C2065: 'name' : undeclared identifier
stackoverflow.cpp(42) : error C2039: 'setRuns' : is not a member of 'std::vector<team,std::allocator<_Ty>>'
with
[
_Ty=team
]
stackoverflow.cpp(43) : error C2039: 'setName' : is not a member of 'std::vector<team,std::allocator<_Ty>>'
with
[
_Ty=team
]
stackoverflow.cpp(45) : error C2039: 'getName' : is not a member of 'std::vector<team,std::allocator<_Ty>>'
with
[
_Ty=team
]
stackoverflow.cpp(45) : error C2039: 'getRuns' : is not a member of 'std::vector<team,std::allocator<_Ty>>'
with
[
_Ty=team
]
Class names of the C++ standard library are prefixed with std::. That's just part of their name. It is good practice to just always use the full name. In particular, it is very bad practice to use using namespace std; at global scope in a header file.
So let's remove using namespace std and write std:: everywhere.
team.h:
#include<string>
class team {
std::string name;
int runs;
public:
void setName(std::string a);
std::string getName();
void setRuns(int b);
int getRuns();
};
team.cpp:
#include<string>
#include "team.h"
void team::setRuns(int b) {
runs=b;
}
void team::setName(std::string a) {
name=b;
}
int team::getRuns() {
return runs;
}
std::string team::getName() {
return name;
}
main.cpp:
#include<iostream>
#include<vector>
#include<cstdio>
#include "team.h"
int main() {
std::vector<team> players[5];
players[0].setRuns(10);
players[0].setName("Michael");
printf("%s %d",players[0].getName(),players[0].getRuns());
system("pause");
return 0;
}
This removes most errors:
stackoverflow.cpp(22) : error C2065: 'b' : undeclared identifier
stackoverflow.cpp(39) : error C2039: 'setRuns' : is not a member of 'std::vector<team,std::allocator<_Ty>>'
with
[
_Ty=team
]
stackoverflow.cpp(40) : error C2039: 'setName' : is not a member of 'std::vector<team,std::allocator<_Ty>>'
with
[
_Ty=team
]
stackoverflow.cpp(42) : error C2039: 'getName' : is not a member of 'std::vector<team,std::allocator<_Ty>>'
with
[
_Ty=team
]
stackoverflow.cpp(42) : error C2039: 'getRuns' : is not a member of 'std::vector<team,std::allocator<_Ty>>'
with
[
_Ty=team
]
The a in setRuns is certainly a typo. We'll also fix that. I'll also just remove the unnecessary system("pause");. Now we have code which exhibits only the error you asked about.
Let's take a closer look at the following line:
std::vector<team> players[5]
I think the misunderstanding here is that [5] specifies the size of the std::vector. This is a misconception. A std::vector has no fixed size and will start at 0 elements by default. It does not need any [] syntax for initialization. The [] syntax here denotes an array. An array is a fixed-size collection of elements.
So what you created here is an array of 5 vectors. Apparently, that's not at all what you wanted. Just replace the [5] with (5) to get the meaning of "vector that starts with 5 elements":
std::vector<team> players(5);
Now it compiles. But it will probably crash at run-time, because you also use printf incorrectly:
printf("%s %d",players[0].getName(),players[0].getRuns());
printf is a C function which was designed long before C++ existed. %s means that a C-style string is expected. You could provide one like this:
printf("%s %d",players[0].getName().c_str(),players[0].getRuns());
Or you just use C++ streams:
std::cout << players[0].getName() << " " << players[0].getRuns();

C++ Inheritance Issues

I am having some issues regarding inheritance. I have a class of Person, and a class of Student:Person, Employee:Person. The errors that I am getting baffle me – I do not understand why I am getting them. I used tiny paste to paste the code as I thought it would take too much space up here. If I should post question elsewhere, let me know. Thanks.
Code Files:
main.cpp – http://tinypaste.com/0775bea3
Person.h – http://tinypaste.com/657638ef
Person.cpp – http://tinypaste.com/934ee106
Student.h – http://tinypaste.com/260fa4bb
Student.cpp – http://tinypaste.com/b6259aa4
Employee.h – http://tinypaste.com/f8b53d36
Employee.cpp – http://tinypaste.com/1d939927
Here are the errors that I am getting:
1>------ Build started: Project: PR4_Students, Configuration: Debug Win32 ------
1>Build started 2/18/2012 11:14:27 PM.
1>InitializeBuildStatus:
1> Touching "Debug\PR4_Students.unsuccessfulbuild".
1>ClCompile:
1> main.cpp
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\student.h(15): error C2969: syntax error : ';' : expected member function definition to end with '}'
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\student.h(16): error C2059: syntax error : 'inline function header'
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\student.h(16): error C2630: ';' found in what should be a comma-separated list
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\employee.h(15): error C2969: syntax error : ';' : expected member function definition to end with '}'
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\employee.h(16): error C2059: syntax error : 'inline function header'
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\employee.h(16): error C2630: ';' found in what should be a comma-separated list
1> Student.cpp
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\student.h(15): error C2969: syntax error : ';' : expected member function definition to end with '}'
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\student.h(16): error C2059: syntax error : 'inline function header'
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\student.h(16): error C2630: ';' found in what should be a comma-separated list
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\student.cpp(8): error C2084: function 'Student::Student(void)' already has a body
1> \\cs1\cs_students\mlindahl15\cs273\pr4_students\student.h(15) : see previous definition of '{ctor}'
1> Employee.cpp
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\employee.h(15): error C2969: syntax error : ';' : expected member function definition to end with '}'
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\employee.h(16): error C2059: syntax error : 'inline function header'
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\employee.h(16): error C2630: ';' found in what should be a comma-separated list
1>\\cs1\cs_students\mlindahl15\cs273\pr4_students\employee.cpp(8): error C2084: function 'Employee::Employee(void)' already has a body
1> \\cs1\cs_students\mlindahl15\cs273\pr4_students\employee.h(15) : see previous definition of '{ctor}'
1> Generating Code...
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:05.64
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I didn't analyze the whole code, but you seem to be confused how to declare calls to the base class constructor;
class Student : public Person
{
...
Student() : Person();
...
};
The call to the base class constructor should be done on the actual implementation of the constructor only. Since you already do that with
Student::Student() : Person() {
you can just change the declaration to
class Student : public Person
{
...
Student();
...
};
and things should turn out better.
Edit: Adding the answer to a follow-up question below;
The line
Employee(string department, string jobTitle, int yearOfHire)
: Person(name, socialSecurityNumber, age, gender, address, phoneNumber) {
does for the same reason not really make sense. If you want to be able to construct an Employee with all those parameters, you need to instead declare the constructor as;
Employee(string department, string jobTitle, int yearOfHire, name,
socialSecurityNumber, age, gender, address, phoneNumber) {
and implement it as
Employee::Employee(string department, string jobTitle, int yearOfHire, name,
socialSecurityNumber, age, gender, address, phoneNumber)
: Person(name, socialSecurityNumber, age, gender, address, phoneNumber) {
thus passing on the parameters to the base class constructor.
At line 15 of Students.h:
Student() : Person();
That's invalid. Either you need to completely define the constructor there, or not at all.
So:
Student() : Person() { some code; };
or:
Student();
and put the actual code in your implementation file.

I need help with properly initlizing a structure and passing it into a function properly

I am writing a simple C++ database, using Visual Studio 2008 express edition, like program to sort and search a text file containing NCAA winners and runner ups by year, this data is to be saved within a structure. I understand how to do the sorting and searching but i am having trouble with properly initializing the structure and passing it into a function, as when i try to do it how i was shown in class i get several errors that i have been unable to get rid of, any help would be greatly appreciated.
The errors are as follows;
project5.cpp(145) : error C2676: binary '[' : 'Data' does not define this operator or a conversion to a type acceptable to the predefined operator
project5.cpp(145) : error C2228: left of '.year' must have class/struct/union
project5.cpp(146) : error C2676: binary '[' : 'Data' does not define this operator or a conversion to a type acceptable to the predefined operator
project5.cpp(146) : error C2228: left of '.schoolWin' must have class/struct/union
project5.cpp(147) : error C2676: binary '[' : 'Data' does not define this operator or a conversion to a type acceptable to the predefined operator
project5.cpp(147) : error C2228: left of '.scoreWin' must have class/struct/union
project5.cpp(148) : error C2676: binary '[' : 'Data' does not define this operator or a conversion to a type acceptable to the predefined operator
project5.cpp(148) : error C2228: left of '.schoolRunnerUp' must have class/struct/union
project5.cpp(149) : error C2676: binary '[' : 'Data' does not define this operator or a conversion to a type acceptable to the predefined operator
project5.cpp(149) : error C2228: left of '.scoreRunnerUp' must have class/struct/union
project5.cpp(191) : error C2664: 'initializeStructure' : cannot convert parameter 1 from 'Data [100]' to 'Data &'
My Structure Declaration:
const int Size = 100; // size of structure
struct Data { // Struct definintion to take in stats
int year;
string schoolWin;
int scoreWin;
string schoolRunnerUp;
int scoreRunnerUp;
} NCAAStats [Size] ;
void initializeStructure(Data& NCAAStats, int Size); // initialization function prototype
//function declaration
void initializeStructure(Data& NCAAStats, int Size) {
int Idx;
for (Idx = 0; Idx < Size; Idx++) {
NCAAStats[Idx].year = 0000;//line145
NCAAStats[Idx].schoolWin = "winning school";//line146
NCAAStats[Idx].scoreWin = 000;//line147
NCAAStats[Idx].schoolRunnerUp = "losing school";//line148
NCAAStats[Idx].scoreRunnerUp = 000;//line149
}
}
//initalize the array of structures
initializeStructure(NCAAStats, Size);//line 191 function call from within main
Based off the last error i was thinking that it is possible that for some reason visual studio thinks my structure is named Data with a size of 100 when, it is NCAAStats of size 100, but i am not sure what i did wrong that is causing this, any suggestions would be greatly appreciated.
Since you tagged C++ I'd suggest you use C++ features...
#include <vector>
#include <string>
struct Data
{
unsigned int year;
std::string schoolWin;
unsigned int scoreWin;
std::string schoolRunnerUp;
unsigned int scoreRunnerUp;
Data()
: year(0)
, schoolWin("winning school")
, scoreWin(0)
, schoolRunnerUp("loosing school")
, scoreRunnerUp(0){}
}
// In main
std::vector<Data> my_data(100); // Create and initialize 100 instances of "Data".
Note this error:
project5.cpp(191) : error C2664: 'initializeStructure' : cannot convert parameter 1 from 'Data [100]' to 'Data &'
The argument NCAAStats you defined for initializeStructure() is a reference to one struct of type NCAAStats, which you can't use like an array (I assume that's what you were going for). You'll have to change it to a pointer (Data * or Data[]) to match the type you're actually passing as an argument.
You have declared an array NCAAStats[Size] at the global scope. However, your functions have arguments called NCAAStats; these hide the global definition. Therefore, stuff like NCAAStats[Idx] is invalid, because that NCAAStats is a Data &, not a Data[].