Accessing nested class in C++ - c++

I came across this question in an online test that I was taking. The task is to alter this program to get rid of compilation errors.
#include<iostream>
#include<iomanip>
class Vehicle
{
public:
static Car* createCar()
{
return new Car;
}
class Car
{
public:
string name;
};
private:
int seats;
};
void useVehicle()
{
Vehicle::Car *c = Vehicle::createCar();
c->name = "BMW";
}
int main(int argc, char *argv[])
{
useVehicle();
return 0;
}
The compilations errors are like:
error: ‘Car’ does not name a type
error: ‘string’ does not name a type
In function void useVehicle():
error: ‘createCar’ is not a member of ‘Vehicle’
How do I get it right ? I tried few things but could not resolve these errors.

error: ‘Car’ does not name a type
At the point of
static Car* createCar()
Car is not yet known. Move the definition of class Car above the function
error: ‘string’ does not name a type In function ‘void useVehicle()’:
#include <string>
also use std:: to qualify string
error: ‘createCar’ is not a member of ‘Vehicle’
This error will disappear once you fix the other two issues. The compiler wasn't able to parse the function declaration because it didn't know what its return type was.

Related

cannot convert 'int (B::*)(std::string)' to 'int (*)(std::string) ' in assignment pt2function=&B::generate_callback;

I am new to c++, .I am trying to create a pgm that contains 2 classes ,out of which one class has a member function that would generate a callback function in another class though a function pointer, but i keep getting the following error.
#include <iostream>
#include <string>
using namespace std;
class B
{
private: std::string str1;
public: int generate_callback(std::string str1);
};
int B::generate_callback(std::string str1)
{
if ((str1=="Generate")||(str1=="generate"))
{
Cout<<"Callback generated ";
}
return 0;
}
class A : public B
{
public:
void count(int a,int b);
private: int a,b;
};
void A::count(int a, int b)
{
for ( a=1;a<b;a++){
if(a==50)
{
cout<<"Generating callback ";
goto exit;
}
exit: ;
}
}
int (*pt2function)(string)=NULL;
int main()
{
B obj1;
A obj2;
string str;
cout<<"To generate callback at int i=50 please enter 'generate'";
cin>>str;
obj2.count(1,100);
pt2function=&B::generate_callback;
(obj1.*pt2function)(str);
return 0;
}
The errors :
main.cpp:57: error: cannot convert 'int (B::*)(std::string) {aka int (B::*)(std::basic_string<char>)}' to 'int (*)(std::string) {aka int (*)(std::basic_string<char>)}' in assignment
pt2function=&B::generate_callback;
/home/adt/practice/N_practise/n_pract_2/pract2/main.cpp:58: error: 'pt2function' cannot be used as a member pointer, since it is of type 'int (*)(std::string) {aka int (*)(std::basic_string<char>)}'
(obj1.*pt2function)(str);
^
^
The variable pt2function is a pointer to a non-member function. Such a pointer is not compatible with a pointer to a member-function. Which is what the compiler tells you with the first error: A int (*)(string) is not compatible with a int (B::*)(string).
You need to define pt2function as a pointer to a B member function:
int (B::*pt2function)(string)=NULL;
Now you can initialize or assign a matching member function of B to the variable pt2function.
This also solves the second errors, which basically says that in your current code the variable pt2function is not a pointer to a member function, and therefore can not be used as such.
Pointers to functions and pointers to member functions are really different beasts.
You have mainly two options to get it working in your code:
Change this line:
int (*pt2function)(string)=NULL;
To this:
int (B::*pt2function)(string)=NULL;
That is defining pt2function as a pointer to a member function of B that gets a string and returns an int.
Declare the generate_callback as a static method and invoke it as pt2function(str); in your main function.
In fact, a static member function can be assigned to a pointer to function like the one you have already in use.

Error in C++ : redefinition of class constructor

I've encountered these two error when trying to compile..
anyone knows whats wrong ?
Was thinking maybe I #include the wrong header file ?
the sample of the codes and error as per following:
Error:
Square.cpp:8: error: redefinition of ‘Square::Square(bool, Point*, std::string, int)’
Square.h:21: error: ‘Square::Square(bool, Point*, std::string, int)’ previously defined here
Square.cpp: In member function ‘Point Square::getCoord()’:
Square.cpp:22: error: expected primary-expression before ‘]’ token
Square.cpp: In member function ‘void Square::setCoord(Point*)’:
Square.cpp:32: error: expected primary-expression before ‘]’ token
Square.cpp:32: error: expected primary-expression before ‘]’ token
cpp file
#include "Square.h"`
#include <cmath>
using namespace std;
Square::Square(bool containsWarpSpace, Point coord[], string shapeName, int vertPoint):ShapeTwoD(shapeName, containsWarpSpace) {
vertPoint = vertPoint;
coord[] = coord[];
}
int Square::getVertPoint()
{
return vertPoint;
}
Point Square::getCoord()
{
return coord[];
}
void Square::setVertPoint(int verticleP)
{
vertPoint = verticleP;
}
void Square::setCoord(Point coord[])
{
coord[] = coord[];
}
header:
#include "ShapeTwoD.h"
class Square : public ShapeTwoD
{
private:
int vertPoint;
Point coord[];
public:
//Accessor
int getVertPoint();
Point getCoord();
//Mutator
void setVertPoint(int vertP);
void setCoord(Point coord[]);
//virtual member
virtual double computeArea(Point x, Point y);
Square(bool containsWarpSpace, Point coord[], std::string shapeName = "Square", int vertPoint = 4):ShapeTwoD(shapeName, containsWarpSpace){}
};
You are defining the constructor twice, once in the header and once in the implementation file. In the header, you just need to declare it like this:
Square(bool containsWarpSpace,
Point coord[],
std::string shapeName = "Square",
int vertPoint = 4);
You also need to fix the handling of coord, maybe something like changing coord to
Point* coord;
and use
Point* Square::getCoord()
{
return coord;
}
and
this->coord = coord;
in the constructor and setCoord().
Please note that your way of handling coord seems strange and dangerous to me, but without further information about what you are actually trying to do it's hard to give specific advise. Generally, consider using the standard containers over manual memory/array management.
The compiler clearly tells you the problem:
You defined the constructor twice once in header file and once in cpp file.
Also, What exactly do you intend to do with:
coord[] = coord[];
You should understand each and every statement of code that you write. Think about, What do you intend this statement to do? & then match it to the language grammar that you learnt.
Source File:
Square::Square(bool containsWarpSpace, Point coord[],
string shapeName, int vertPoint)
:ShapeTwoD(shapeName, containsWarpSpace)
{
vertPoint = vertPoint;
coord[] = coord[];
}
Header File:
Square(bool containsWarpSpace, Point coord[],
std::string shapeName = "Square", int vertPoint = 4)
:ShapeTwoD(shapeName, containsWarpSpace)
{}
Looks like two different version of the same function.
The one in the header file calls the base class constructor but does not have any code in the body of the constructor.

c++ Set not compiling properly

I am creating a data structure but when I try and compile I get an error saying that I haven't specified that type of set that I am initializing.
I am working with the NTL library with is used for large numbers.
This is my code:
#include <set>
#include ...
NTL_CLIENT
using namespace std;
using namespace NTL;
const RR ZERO = to_RR(0);
const RR ONE = to_RR(1);
const RR TWO = to_RR(2);
class tenTree
{
public:
tenTree(string newName = "", int newLevel = 0);
~tenTree();
void put(string prefix, RR power);
bool get(string prefix, RR & output);
void display(int depth);
bool isKnown(RR power){return (powers.find(power) != powers.end());};
private:
tenTree* children [10];
set<int> powers;
int level;
string name;
bool child[10];
};
When I try to compile it comes back with an error saying:
twoPow.cpp:47: error: ISO C++ forbids declaration of \u2018set\u2019 with no type
twoPow.cpp:47: error: expected \u2018;\u2019 before \u2018<\u2019 token
twoPow.cpp: In member function \u2018bool tenTree::isKnown(NTL::RR)\u2019:
twoPow.cpp:44: error: \u2018powers\u2019 was not declared in this scope
Is there something that I am missing here?
It was just a matter of the scope. All I had to do was add an std:: before the set and it compiled correctly.

How to build a binary from multiple c++ files?

I have started learning C++, and have gotten stuck when working with multiple files. To practice basic classes, I wrote three different files,
working.cpp
word.cpp
word.h
word.cpp:
#include <iostream>
#include "word.h"
using namespace std;
class word{
public:
char *word;
void createWord(char *str)
{
word = str;
}
void print_word(void)
{
cout<<word<<endl;
}
char * getWord()
{
return word;
}
}
working.cpp
#include <iostream>
#include "word.h"
void printWord(word);
using namespace std;
int main()
{
word one;
one.createWord("one");
printWord(one);
}
void printWord(word a)
{
cout<<a.getWord()<<endl;
}
word.h
class word;
These are three different files, so I am not sure how to compile them. What I have tried is
g++ working.cpp word.cpp
However, the compiler doesn't recognize word as a class, and gives me the following errors
working.cpp: In function 'int main()':
working.cpp:7:7: error: aggregate 'word one' has incomplete type and cannot be defined
working.cpp:7:12: error: aggregate 'word two' has incomplete type and cannot be defined
working.cpp:7:17: error: aggregate 'word three' has incomplete type and cannot be defined
working.cpp: In function 'void printWord(word)':
working.cpp:19:6: error: 'aha' has incomplete type
In file included from working.cpp:2:0:
word.h:2:7: error: forward declaration of 'class word'
word.cpp:25:1: error: expected ';' after class definition
What am I doing wrong while compiling?
You need to include more of the definition of word in the header file. Something like this:
class word
{
public:
char *word;
void createWord(char *str);
void print_word(void);
char * getWord();
};
Then, change word.cpp to just have the implementations:
void word::createWord(char *str)
{
word = str;
}
void word::print_word(void)
{
cout<<word<<endl;
}
char * word::getWord()
{
return word;
}
compile and link!
You need to have more of the word class in the header so that your other translation unit can know how big the class is (to reserve enough space for the instance you're creating) as well as to know the names of the methods you want to call.
Just mentioning the class name in the header file (a so-called forward declaration) is not enough; you need a complete class declaration (which declares all the fields and functions of the class):
class word {
public:
char *word;
void createWord(char *str);
void print_word(void);
char * getWord();
};
There is no actual declaration of class word in word.h
word.h:2:7: error: forward declaration of 'class word'
I would advise you to read Bjarne Stroustrup's brilliant book "The C++ Programming Language" to get started.

How to properly use a header file to be a complete class?

(Beginner programmer..) I'm following the style of a header file that worked fine, but I'm trying to figure out how I keep getting all of these errors when I compile. I am compiling with g++ in Cygwin.
Ingredient.h:8:13: error: expected unqualified-id before ‘)’ token
Ingredient.h:9:25: error: expected ‘)’ before ‘n’
Ingredient.h:19:15: error: declaration of ‘std::string <anonymous class>::name’
Ingredient.h:12:14: error: conflicts with previous declaration ‘std::string<anonymous class>::name()’
Ingredient.h:20:7: error: declaration of ‘int <anonymous class>::quantity’
Ingredient.h:13:6: error: conflicts with previous declaration ‘int<anonymous class>::quantity()’
Ingredient.h: In member function ‘std::string<anonymous class>::name()’:
Ingredient.h:12:30: error: conversion from ‘<unresolved overloaded function type>’ to non-scalar type ‘std::string’ requested
Ingredient.h: In member function ‘int<anonymous class>::quantity()’:
Ingredient.h:13:25: error: argument of type ‘int (<anonymous class>::)()’ does not match ‘int’
Ingredient.h: At global scope:
Ingredient.h:4:18: error: an anonymous struct cannot have function members
Ingredient.h:21:2: error: abstract declarator ‘<anonymous class>’ used as declaration
And here is my class header file...
#ifndef Ingredient
#define Ingredient
class Ingredient {
public:
// constructor
Ingredient() : name(""), quantity(0) {}
Ingredient(std::string n, int q) : name(n), quantity(q) {}
// accessors
std::string name() { return name; }
int quantity() {return quantity; }
// modifier
private:
// representation
std::string name;
int quantity;
};
#endif
I am confused by these errors and don't really know what I am doing wrong concerning the implementation of the class..
That's a funny one. You are essentially killing your class name by #define Ingredient - all occurrences of Ingredient will be erased. This is why include guards generally take the form of #define INGREDIENT_H.
You are also using name both for the member and the getter function (probably an attempt to translate C#?). This is not allowed in C++.
How about look on errors? variables and functions can't have same names. And include guard should never names such as class.
#ifndef INGREDIENT_H
#define INGREDIENT_H
class Ingredient {
public:
// constructor
Ingredient() : name(""), quantity(0) {}
Ingredient(std::string n, int q) : name(n), quantity(q) {}
// accessors
std::string get_name() const { return name; }
int get_quantity() const {return quantity; }
// modifier
private:
// representation
std::string name;
int quantity;
};
#endif