No matching conversion for functional-style cast from 'B *' to 'std::shared_ptr<A>' - class

I have a simple appliction that tries to initialize a shared ptr.
#include <iostream>
#include <memory>
#include <algorithm>
class A {
public:
A(){
std::cout << "default ctor for A" << std::endl;
}
~A(){
std::cout << "default dtor for A" << std::endl;
}
};
class B : A{
B(){
std::cout << "default ctor for B" << std::endl;
}
~B(){
std::cout << "default dtor for B" << std::endl;
}
};
int main()
{
auto ap = std::shared_ptr<A>(new B());
return 0;
}
I am getting the error
No matching conversion for functional-style cast from 'B *' to 'std::shared_ptr<A>'
in this line
auto ap = std::shared_ptr(new B());
What am I doing wrong here?

Class B should be declared like
class B : public A{
public:
B(){
std::cout << "default ctor for B" << std::endl;
}
~B(){
std::cout << "default dtor for B" << std::endl;
}
};

Related

Segmentation Error: Help on the correct allocation memory when saving & loading binary files containing a specific structure from a class

This is my first time asking a question, so apologies if it is not done 100%:
I have a class which saves and loads a binary file with a specific data structure.
If the program creates an instance of the class, save the binary file, and creates another instance of the class to load/read the binary file consequently, everything seems 100% correct.
However, if I run the program to save the binary file and then run it again to load/read that binary file, it gives me a segmentation fault at the end.
The program still does everything it needs to do before the segmentation fault, except deconstructing the class at the end (obviously).
It looks like my allocation of the memory is not correct, but I am not sure where I am going wrong.
A simplified version of the code follow (also here: https://github.com/LenteDreyer/Tests.git )
Can someone see where I am going wrong?
class header file that save/loads the file
#ifndef __TESTS_MAP_HH__
#define __TESTS_MAP_HH__
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
typedef struct test_struct{
bool test_bool;
double test_double;
std::vector<double> test_vector;
} test_struct_t;
class map
{
private:
std::string m_path, m_str;
double m_double;
test_struct m_struct;
public:
map(const std::string& a_id);
void set_str(std::string a_str);
void set_double(double a_double);
void set_struct(test_struct a_struct);
void load_file();
void save_file() const;
void show_file() const;
~map();
};
#endif //__TESTS_MAP_HH__
class source file that save/loads the binary file
#include "map.hh"
map::map(const std::string& a_id)
{
m_path = a_id + ".bin";
m_str = "none";
m_double = 0.0;
m_struct = {false, 0.0};
}
void map::set_str(std::string a_str){
m_str = a_str;
}
void map::set_double(double a_double){
m_double = a_double;
}
void map::set_struct(test_struct a_struct){
m_struct = a_struct;
}
void map::load_file(){
std::ifstream l_inF;
l_inF.open(m_path.c_str(), std::ios::binary | std::ios::in);
l_inF.read((char*)&m_double,sizeof(double));
l_inF.read((char*)&m_struct,sizeof(test_struct_t));
size_t str_size;
l_inF.read((char*)&str_size, sizeof(str_size));
m_str.resize(str_size);
l_inF.read((char*)&m_str[0], str_size);
l_inF.close();
}
void map::save_file() const{
std::ofstream l_outF;
l_outF.open(m_path.c_str(), std::ios::binary | std::ios::out);
l_outF.write((char*)&m_double,sizeof(double));
l_outF.write((char*)&m_struct,sizeof(test_struct_t));
size_t str_size = m_str.size();
l_outF.write((char*)&str_size, sizeof(str_size));
l_outF.write((char*)&m_str[0], str_size);
l_outF.close();
}
void map::show_file() const{
std::cout << ">>-----------------------------------------------" << std::endl;
std::cout << ">> double : " << m_double << std::endl;
std::cout << ">> double : " << m_double << std::endl;
std::cout << ">> struct.bool : " << m_struct.test_bool << std::endl;
std::cout << ">> struct.double : " << m_struct.test_double << std::endl;
std::cout << ">> struct.vector : " << "size = " << m_struct.test_vector.size() << std::endl;
std::cout << ">> string : " << m_str << std::endl;
std::cout << ">>-----------------------------------------------" << std::endl;
}
map::~map(){}
main function case 1 works, and case 2 gives the segmentation fault.
#include "map.hh"
int main(int argc, char const *argv[])
{
std::string id = "mapfile";
int action = 0;
if(argc > 1) action = std::stoi(argv[1]);
else {
std::string input;
std::cout << "Enter case (1 or 2): ";
std::cin >> input;
action = std::stoi(input);
}
switch (action)
{
case 1:
{
// This works 100% (no errors and it saves/reads class perfectly)
std::vector<double> l_vect = {0.1, 0.0, 0.6};
test_struct save_struct = {true, 5.0, l_vect};
map test_save(id);
test_save.show_file();
test_save.set_double(8.0);
test_save.set_str("save this string");
test_save.set_struct(save_struct);
test_save.show_file();
test_save.save_file();
map test_load(id);
test_load.load_file();
test_load.show_file();
}
break;
case 2:
{
// gives segmentation error at the end of the program
map test_load(id);
test_load.load_file();
test_load.show_file();
}
break;
default:
break;
}
return 0;
}

Question about the What's In the Box code game assignment

I am struggling to understand how to properly use pass by value and reference in this program. It keeps saying identifier is undefined when I put the Int in the main function. But when it's out of the main function it works fine. I can't use it outside of the main function otherwise it's an automatic 0. Am I just missing code that identifies it?
I didn't explain the program very well. It's essentially the Monty Hall problem but with boxes. The user then tries to guess the right box. The biggest issue I had was getting the non prize box to appear to the user in the output.
I am very new to coding so I am probably overlooking something.
#include <stdlib.h>
#include <iomanip>
#include <iostream>
#include <time.h>
#include <string>
using namespace std;
/*******************************************************************************
* Function Name: main()
* Parameters: None
* Return Value: int
* Purpose: To execute the main function of the program. Performs loops and takes user input to execute the game.
*****************************************************************************/
void BoxCheck(int);
void PrizeBox(int&);
//int UserGuess = 0;
int main()
{
int UserChoice;
int UserGuess;
int BoxReveal;
int PrizeB;
// int Prize;
//char Switch;
cout << "Wellcome to Pandora's Prize!" << endl;
cout << "Infront of you there are three doors, and behind one of them is the grand prize!" << endl;
cout << "But in the the other two they contain a stink bomb." << endl;
cout << "It's your job to guess which one has the prize behind it." << endl;
cout << "Door 1?" << endl;
cout << "Door 2?" << endl;
cout << "Door 3?" << endl;
PrizeBox(PrizeB);
cin >> UserGuess;
BoxReveal != (PrizeB || UserGuess);
// cout << "The host revealed box number " << BoxReveal << " ." << endl;
//if (true)
//{
if (UserGuess == 1)
{
cout << "You picked box 1." << endl;
cout << "The host revealed box number " << BoxReveal << " ." << endl;
cout << "Would you like to stay with box number 1 or switch." << endl;
//cin >> UserChoice;
}
else if (UserGuess == 2)
{
cout << "You picked box 2." << endl;
cout << "The host revealed box number " << BoxReveal << " ." << endl;
cout << "Would you like to stay with box number 2 or switch." << endl;
//cin >> UserChoice;
}
else if (UserGuess == 3)
{
cout << "You picked box 3." << endl;
cout << "The host revealed box number " << BoxReveal << " ." << endl;
cout << "It contains a red snapper!" << endl;
cout << "Would you like to stay with box number 3 or switch." << endl;
//cin >> UserChoice;
}
else
{
cout << "This isn't a number associated with a box. Try again." << endl;
}
//}
/* if (true)
{
} */
//PrizeBox(Prize);
if (UserChoice == UserGuess)
{
cout << "You chose to stay with your original box." << endl;
BoxCheck(UserGuess);
}
else if (UserChoice != UserGuess) //|| UserChoice != BoxReveal)
{
cout << "You decided to switch." << endl;
BoxCheck(UserGuess);
}
/*else if (UserChoice != UserGuess || BoxReveal)
{
cout << "You decided to switch." << endl;
BoxCheck(UserGuess);
} */
else
{
cout << "Your answer was out of the parameters." << endl;
BoxCheck(UserGuess);
}
//BoxCheck(UserGuess);
system("pause");
return 0;
}
void PrizeBox(int& PrizeB)
{
srand(time(NULL));
PrizeB = rand() % 3 + 1;
//Prize = rand() % 3 + 1;
//cin >> PrizeB;
/* BoxReveal = !(PrizeBox || boxChoice);
cout << "Here is one of the box's opened! " << boxReveal << " ." << endl;
BSwitch = (boxChoice || boxReveal); */
}
void BoxCheck(int UserChoice)
{
if (UserChoice == PrizeB)
{
cout << "WOW YOU WON!!!!" << endl;
}
else if (UserChoice != PrizeB)
{
cout << "Sorry you got a red snapper" << endl;
}
else
{
cout << "Sorry you got a red snapper" << endl;
}
}

C++ class casting

Guys I am trying to create an object that can instantiate the other types that inherit it:
#include <iostream>
#include <cstdlib>
class Animal {
public:
char *nome;
Animal (char *nome) {
this->nome = nome;
}
};
class Cachorro : public Animal {
public:
bool enterraOsso;
Cachorro (char* nome, bool enterraOsso) : Animal(nome) {
this->enterraOsso = enterraOsso;
}
};
class Passaro : public Animal {
public:
bool voar;
Passaro (char* nome, bool voar) : Animal(nome) {
this->voar = voar;
}
};
int main() {
Animal *animal;
animal = new Cachorro("Scooby", true);
std::cout << animal->nome << ", " << animal->enterraOsso << std::endl;
animal = new Passaro("Piopio", false);
std::cout << animal->nome << ", " << animal->voar << std::endl;
return 0;
}
The idea is to access the subclass attributes from the superclass also.
I don't know if this is a cast or polymorphism, in Java I know it is possible, but can't do it in C++.
Thank you for all your help.
You can, it is bad design though for a Base class to know about its children:
int main() {
Animal *animal;
animal = new Cachorro("Scooby", true);
Cachorro * c = reinterpret_cast<Cachorro*>(animal);
std::cout << animal->nome << ", " << c->enterraOsso << std::endl;
animal = new Passaro("Piopio", false);
Passaro * p = reinterpret_cast<Passaro*>(animal);
std::cout << animal->nome << ", " << p->voar << std::endl;
}

Template class method error "no 'void Pair<T1, T2>::display()' member function Pair declared in class"

I'm not sure if my syntax is incorrect. I am getting "no 'void Pair T1, T2::display()' member function Pair declared in class" as well as "no matching function for call to ‘Pair std::basic_string char, std::char_traits char" Here is the header file:
#ifndef PAIR_H
#define PAIR_H
#include <iostream>
#include <string>
using namespace std;
template <typename T1, typename T2 >
class Pair
{
private:
T1 t1;
T2 t2;
public:
Pair(const T1 & t1,const T2 & t2) : t1(t1), t2(t2) {};
T1 getFirst() const { return t1; };
T2 getSecond() const { return t2; };
//setters
void setFirst(const T1 & value) { t1 = value; };
void setSecond(const T2 & value) { t2 = value; };
};
template <typename T1, typename T2>
void Pair<T1,T2> :: display()
{
cout << t1 << " - " << t2 << endl;
}
#endif // PAIR_H
and this is the driver file.
#include <iostream>
#include <string>
using namespace std;
#include "pair.h"
int main()
{
string first;
cout << "Please enter a first name: ";
cin >> first;
string last;
cout << "Please enter a last name: ";
cin >> last;
Pair<string, string> fullName;
fullName.setFirst(first);
fullName.setSecond(last);
cout << "The first name is: " << fullName.getFirst() << endl;
cout << "The last name is: " << fullName.getSecond() << endl;
cout << "The complete pair is: ";
fullName.display();
cout << endl << endl;
int num1;
cout << "Please enter a number: ";
cin >> num1;
int num2;
cout << "Please enter another number: ";
cin >> num2;
Pair<int, int> numbers;
numbers.setFirst(num1);
numbers.setSecond(num2);
cout << "The first number is: " << numbers.getFirst() << endl;
cout << "The second number is: " << numbers.getSecond() << endl;
cout << "The complete pair is: ";
numbers.display();
cout << endl << endl;
string name;
cout << "Please enter a name: ";
cin >> name;
int score;
cout << "Please enter a score: ";
cin >> score;
Pair<string, int> grade;
grade.setFirst(name);
grade.setSecond(score);
cout << "The name is: " << grade.getFirst() << endl;
cout << "The score is: " << grade.getSecond() << endl;
cout << "The complete pair is: ";
grade.display();
cout << endl << endl;
return 0;
}
Yes, your syntax is incorrect.
1) display() is a member of Pair, so you must declare it inside the class.
You can add this declaration line in the public section
void display ();
or you can define display() inside the class (deleting the definition outside) [I added the const modifier]
void display () const { cout << t1 << " - " << t2 << endl; }
1 bis)
I suggest you to define the operator<< (output operator) for class Pair; something like, inside public, this
friend ostream & operator<< (ostream & os, Pair const & p)
{ return os << '(' << p.t1 << ',' << p.t2 << ')'; }
so you can simply output a pair like this
cout << fullName << endl;
2) You don't define a default constructor (without arguments), so you should define you pairs in this way
Pair<string, string> fullName("", "");
Pair<int, int> numbers(0, 0);
Pair<string, int> grade("", 0);
or, avoiding the following setFirst() and setSecond()
Pair<string, string> fullName(first , last);
Pair<int, int> numbers(num1, num2);
Pair<string, int> grade(name, score);
3) I don't know if you know it but there is a standard std::pair class (#include <utility>).
4) You should use che c++ tag for a question like this
5) Sorry for my bad English

C++ Why doesn't my constructor work?

I'm using visual c++ 2010 and I'm having trouble with class constructors. I've written it exactly as my instructor described and I can't seem to figure out why it wont compile.
#include <iostream>;
using namespace std;
class Account
{
public:
Insert other functions here...
Account(float b)
{
Balance = b;
}
private:
float &Balance;
}
Int main()
{
float withdraw,deposit;
Account myAccount(100.00);
cout << "Enter the amount you would like to withdraw:" << endl;
cin >> withdraw;
MyAccount.debt(withdraw);
cout << "Your balance is now "<< endl;
MyAccount.showAccountInfo();
cout << endl;
cout << "Enter the amount you would like to deposit: " << endl;
cin >> deposit;
myAccount.credit(deposit);
cout << "Your balance now is " << endl;
MyAccount.showAccountInfo();
cout << endl;
return 0;
}
It is possible that you have declared the member Balance as a reference and you are calling the constructor with a constant (i.e. 100.00), you must pass a variable name to the contructor or declare the member without the reference operator.
If you need the balance in different parts of the process you could try it with dynamic memory.
For instance:
class Account
{
public:
Insert other functions here...
Account(float* b)
{
Balance = b;
}
private:
float* Balance;
}
Int main()
{
float withdraw,deposit;
Account myAccount(new float(100.0));
cout << "Enter the amount you would like to withdraw:" << endl;
cin >> withdraw;
MyAccount.debt(withdraw);
cout << "Your balance is now "<< endl;
MyAccount.showAccountInfo();
cout << endl;
cout << "Enter the amount you would like to deposit: " << endl;
cin >> deposit;
myAccount.credit(deposit);
cout << "Your balance now is " << endl;
MyAccount.showAccountInfo();
cout << endl;
return 0;
In the updating balance method, you should unreference the pointer:
For instance...
void debt(float withdraw){
*balance -= withdraw;
}
Thanks, Regards.