initializing string in class using constructor - visual-c++

I am creating a class that has two members string and int
I want to use the constructor to initialize both of these two members to use them.
#pragma once
#include <string>
#include <iostream>
using namespace std;
class donation_1
{
public:
//string name;
const char* name;
int donation_amount;
const static size_t string_size = sizeof(string);
const static size_t int_size = sizeof(int);
donation_1(char* name_1 = "Noname", int amount = 0) : name(name_1), donation_amount(amount) {};
};
int main()
{
fstream file;
file.open("donation_total1.txt", ios_base::app);
if (file.is_open())
{
donation_1("xxxx", 20).writedata(file);
donation_1("yyyy", 30).writedata(file);
donation_1("zzzz", 40).writedata(file);
donation_1("MMMM", 50).writedata(file);
donation_1("BBBB", 60).writedata(file);
file.close();
}
else
{
cout << "file couldn't be opened" << endl;
}
return 0;
}
I want to use the constructor to initialize the class variables which I will be using to update a file, however, what I am getting is this error. this error is regarding initializing the string class member.
Severity Code Description Project File Line Suppression State
Error (active) E0310 default argument of type "const char *" is incompatible with parameter of type "char *" Stream_File_Lab D:\INVSPRIVATE\C++\Projects\Stream_File_Lab\donation_1.h 17

The error message is makes it pretty clear. The variable 'name' is declared as const char* but the value being assigned to it is only char* i.e. the const-ness is missing, hence the type incompatibility error throws up.
Please, google for pointer to a const value and how to use them.
Maybe check this tutorial

Related

Error invalid conversion from 'const char*' to 'char*'

I Expect to get the name which I sent to the "class stud" which has a class variable CHAR name
The issue appears specifically at this line this->name->set_name_send(OBJ.name->get_name());
and I get this error " -- invalid conversion from 'const char*' to 'char*' -- "
Any suggestions?
enter image description here
If I make the function set_name as a const and delete the pointers in the destructor code runs but return value is garbage and it has to be 0
Maybe the class *name doesn't have to be pointer ?
All pointer and in OOP
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <iomanip>
using namespace std;
class CHAR
{
char *name;
public:
CHAR(char *mes = "\0") {(this)->name = new char[100]; strcpy((this)->name,mes);}
CHAR(const CHAR&OBJ) { (this)->name = new char[100]; strcpy((this)->name,OBJ.name); }
~CHAR(){cout<<"CHAR Destructor!"<<endl; delete name;}
void set_name(char *mes){(this)->name = new char[100]; strcpy((this)->name,mes);}
const char* get_name() const {return (this)->name;}
};
class stud
{
CHAR *name;
public:
stud(char *mes)
{
this->name->set_name(mes);
}
stud( stud&OBJ)
{
this->name->set_name(OBJ.name->get_name()); //!!!!!!!!!!!!!!! issue HERE!!
}
~stud(){cout<<"Destructor!"<<endl;}
const char* get_name() const {return this->name->get_name();}
};
int main()
{
stud S("John");
stud A(S);
cout<<"Name: "<<A.get_name()<<endl;
}

Visual C++ doesn't see my class

I was trying to make a basic class program to practice making classes, however even though I followed a tutorial visual ++ says Person() expression must have a class type.
I don't really understand what it's saying and didn't find anything after looking it up. here is my code:
//My main program
// ConsoleApplication1.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Person.h"
using namespace std;
int main(){
Person person();
cout << person.getName() << "Age = " << person.getAge() << endl;
return 0;
}
//My person.cpp file
#include "stdafx.h"
#include "person.h"
Person::Person() {
name = "unknown";
age = 0;
}
string Person::getName() {
return "person's name is " + name;
}
int Person::getAge() {
return age;
}
//My person.h file
#pragma once
#include "Person.cpp"
#include <iostream>
#include <string>
using namespace std;
class Person {
private:
string name;
int age;
public:
Person();
string getName();
int getAge();
};
To expand on what #Igor Tandetnik is saying when you are creating the instance of Person you are actually declaring a function which is called person and returns a data type of Person. This function takes no parameters, hence: (). What you want to do is
int main(){
Person person;
//...
//...
}
doing it this way creates an instance of a Person called person, or in easier terms creating a Person called bob would be Person bob; and not Person bob();

Using c++11's std::async inside an abstract base class

Why doesn't making threads like this work inside of an abstract base class? I'm trying to abstract away all of the multithreading details for users who derive from this base class. I don't understand why it says "no type named 'type'" when I clearly write that callbackSquare returns type int.
#include <iostream>
#include <future>
#include <vector>
class ABC{
public:
std::vector<std::future<int> > m_results;
ABC(){};
~ABC(){};
virtual int callbackSquare(int& a) = 0;
void doStuffWithCallBack();
};
void ABC::doStuffWithCallBack(){
for(int i = 0; i < 10; ++i)
m_results.push_back(std::async(&ABC::callbackSquare, this, i));
for(int j = 0; j < 10; ++j)
std::cout << m_results[j].get() << "\n";
}
class Derived : public ABC {
Derived() : ABC() {};
~Derived(){};
int callbackSquare(int& a) {return a * a;};
};
int main(int argc, char **argv)
{
std::cout << "testing\n";
return 0;
}
The strange errors I'm getting are:
/usr/include/c++/5/future:1709:67: required from 'std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...) [with _Fn = int (ABC::*)(int&); _Args = {ABC*, int&}; typename std::result_of<_Functor(_ArgTypes ...)>::type = int]'
/usr/include/c++/5/future:1725:19: required from 'std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(_Fn&&, _Args&& ...) [with _Fn = int (ABC::*)(int&); _Args = {ABC*, int&}; typename std::result_of<_Functor(_ArgTypes ...)>::type = int]'
/home/taylor/Documents/ssmworkspace/callbacktest/main.cpp:16:69: required from here
/usr/include/c++/5/functional:1505:61: error: no type named 'type' in 'class std::result_of<std::_Mem_fn<int (ABC::*)(int&)>(ABC*, int)>'
typedef typename result_of<_Callable(_Args...)>::type result_type;
^
/usr/include/c++/5/functional:1526:9: error: no type named 'type' in 'class std::result_of<std::_Mem_fn<int (ABC::*)(int&)>(ABC*, int)>'
_M_invoke(_Index_tuple<_Indices...>)
Your problem can be reproduced with any function that accepts a reference:
#include <future>
int f(int& a)
{
return a * a;
}
int main()
{
int i = 42;
auto r = std::async(f, i);
}
Accepting a reference in your code is risky since the variable will be modified by the loop iteration, creating a data race because the called function also accesses the variable.
Change the function to accept the input parameter by value, or call std::async by passing std::ref(i) or std::cref(i) (in case the function accepts a const reference) if you acknowledge the risk.

Error reading characters of string

I had a problem while trying to equal one string to another, I get this error "Error reading characters of string." in Visual Studio 2015, in the line that i am doing this "student_name=otherStudent.student_name;" and I just don't get it.
could you please help me?
Student& Student::operator=(const Student &otherStudent) {
if (this != &otherStudent) // Avoid self assignment
{
student_name=otherStudent.student_name;
for (int i = 0; i < grades_size; i++) {
grades[i] = otherStudent.grades[i];
subjet_names[i] = otherStudent.subjet_names[i];
}
average_grade = otherStudent.average_grade;
}
return *this;
}
Here is the definition of the class if it helps:
#include <iostream>
#include <string>
using namespace std;
#define grades_size 6
class Student {
private:
string student_name;
float grades[grades_size];
string subjet_names[grades_size];
float average_grade;
public:
//Constructor
Student();
Student(string name);
//Print status of Student
void printStudent();
//Operator Overloads
Student & operator=(const Student & otherStudent);
};

Question about calling method inside custom IO operator in C++?

I have the following code:
#include "iostream"
#include "conio.h"
using namespace std;
class Student {
private:
int no;
public:
Student(){}
int getNo() {
return this->no;
}
friend istream& operator>>(istream& is, Student& s);
friend ostream& operator<<(ostream& os, const Student& s);
};
ostream& operator<<(ostream& os, const Student& s){
os << s.getNo(); // Error here
return os;
}
int main()
{
Student st;
cin >> st;
cout << st;
getch();
return 0;
}
When compiling this code, the compiler produced the error message: "error C2662: 'Student::getNo' : cannot convert 'this' pointer from 'const Student' to 'Student &'"
But if I made the no variable public and change the error line like: os << s.no; then things worked perfectly.
I do not understand why this happened.
Can anyone give me an explanation, please?
Thanks.
Because s is const in that method, but Student::getNo() isn't a const method. It needs to be const.
This is done by changing your code as follows:
int getNo() const {
return this->no;
}
The const in this position means that this entire method does not change the contents of this when it is called.

Resources