A program based on constructors
Error -Incompatible Type conversion from char to char[100]
Code -
#include<iostream>
using namespace std;
class demo
{
public:
char name[100];
//This is where char is declared
int marks;
demo()
{
marks = 0;
name = "Pro";
//assigning value to the char
cout<<"Working"<<endl;
}
void input()
{
cout<<"Enter Name and Marks"<<endl;
cin>>name>>marks;
}
void output()
{
cout<<name<<"\t"<<marks<<endl;
}
};
i tried putting name in 'name' and "name"
also i tried using type casting (char)
but it didnt seem to work
int main()
{
demo Obj1, Obj2;
//creating objects
Obj1.output();
Obj2.input();
Obj2.output();
return 0;
}
Arrays do not have the copy assignment operator.
So this statement in the constructor
name = "Pro";
is wrong.
You have to write
#include <cstring>
//...
std::strcpy( name, "Pro" );
Or a simpler way is just to rewrite the constructor like
demo() : name { "Pro" }, mark( 1 )
{
cout<<"Working"<<endl;
}
Related
OK here is my code. I have struct named employee and it has a member char* name. How do I change the value of name?
struct employee {
char* name;
int age;
};
int main()
{
struct employee james;
james.age=12; // this line is fine
james.name = "james"; // this line is not working
cout << james.name;
return 0;
}
Use std::string instead of char* pointer, it will work fine
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
Or
If you want to use char* pointer then use const char* name it will work.
#include <iostream>
struct employee {
const char* name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
Any literal string value you enter into your source code (such as "james") is by definition a const char* value, the const meaning it may not be altered at program runtime. In your class the name member is declared to be of type char* which is not const and so may be altered at runtime. Your compiler does not allow you to assign a const char* value to a variable of type char* to maintain the invariant that a value of type const char* may not be modified. (The other way around is fine of course; you may assign a char* value to a variable of type const char*.
To fix this with the fewest characters, you must change char* name to const char* name in your employee struct definition. However, I agree that the best thing to do is change it to a std::string member as #Hamza.S laid out in their answer. The std::string class has an assignment operator that builds it out of a const char* value, so the line james.name = "james" in their answer essentially sets the std::string equal to the const char* value "james".
If you are keen on using char*, you could do something like this :
#include <iostream>
#include <string.h>
#include <stdlib.h>
struct employee {
char *name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = (char *)malloc(sizeof(char) * 10);
strcpy(james.name, "James");
std::cout << james.name << std::endl;
return 0;
}
Or else you could use std::string in your struct like this :
#include <iostream>
#include <string>
struct employee {
std::string name;
int age;
};
int main() {
employee james;
james.age=12;
james.name = "james";
std::cout << james.name;
return 0;
}
You can try using strcpy
strcpy(james.name, "james");
I have a class BankAccount with two string members - name and num. What I want is to assign values to these objects when I create them (when the constructor is called). However the compiler says No instance of constructor matches the argument list when I try to create an object.
I would like to ask why is that?
// hwk-2.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include "pch.h"
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
class BankAccout {
char name[23];
char num[15];
double sum;
public:
BankAccout(char *nm, char *nr, double s) {
strcpy(name,nm);
strcpy(num, nr);
sum = s;
}
};
int main()
{
BankAccout k("Peter", "0403940940", 34.21);
}
as a coffee break exercise here is more idiomatic version
#include "pch.h"
#include <iostream>
#include <string>
class BankAccount {
std::string name_;
std::string num_;
double sum_;
public:
BankAccount(std::string name, std::string num, double sum) {
name_ = name;
num_ = num;
sum_ = sum;
}
};
int main()
{
BankAccount k("Peter", "0403940940", 34.21);
}
The signature of the constructor does not match.
This one will match:
BankAccount(const char *nm, const char *nr, double s);
EDIT:
The reason is the way you are calling the constructor in the main function. You are giving literal strings as parameters. These literals are const, you cannot change them at runtime. Thus you will pass pointers to const char*.
This is very obvious if you look at this opposing example. This is a way that would be compatible with the old signature BankAccout(char *nm, char *nr, double s);.
int main(int argc, char* argv[])
{
char name[] = "hello";
char number[] = "1234";
std::cout << "name before: " << name << std::endl;
BankAccount k(name, number, 8.5);
// name and number are not const,
// you can change them :
name[2] = 'x';
name[3] = 'x';
std::cout << "name after: " << name << std::endl;
return 0;
}
An even simpler version, if you don’t need to have additional functionality in the class: just use a struct.
#include <string>
struct BankAccount {
std::string name;
std::string number;
double balance;
};
int main() {
BankAccount account{"Joy", "44", 43.};
}
I am trying to print out a C string that is stored in a class by returning the value using an accessor function.
Thanks for any help!
This is the error I get when I compile:
cstringClass.cpp: In member function 'char Foo::get_name()':
cstringClass.cpp:37:9: error: invalid conversion from 'char*' to 'char' [-fpermi
ssive]
return name;
^
Here is the code:
#include <iostream>
#include <cstring>
using namespace std;
class Foo
{
public:
void set_name(char a[]);
char get_name();
private:
char name[10];
};
int main()
{
Foo bar;
char a[10] = "Test";
bar.set_name(a);
cout << bar.get_name();
return 0;
}
void Foo::set_name(char a[])
{
strcpy(name, a);
}
char Foo::get_name()
{
return name;
}
So the error says:
cstringClass.cpp: In member function 'char Foo::get_name()':
^^^^^^^^^^^^^^^^^^^^
And indeed:
char get_name();
You declared get_name as returning a single char, not a pointer to a string. You probably meant char *get_name();.
As the error message states, your get_name() function doesn't return the appropriate type, which should be char* based on the data it returns, which is name[10]. char returns only 1 byte of data and name[10] has 10. Please see the corrected code below.
#include <iostream>
#include <cstring>
using namespace std;
class Foo
{
public:
void set_name(char a[]);
char *get_name(); //<-- correction
private:
char name[10];
};
int main()
{
Foo bar;
char a[10] = "Test";
bar.set_name(a);
cout << bar.get_name();
return 0;
}
void Foo::set_name(char a[])
{
strcpy(name, a);
}
char *Foo::get_name() //<-- correction
{
return name;
}
I have designed the class as below
But i am getting runtime error while executing it.
Please let me know the solutions for the below
Why does Line3 in main gives compilation errors (what do i need to do if i want to initialize only one member of the class)
Why do i get run time error for Line 4.
Code:
#include <stdio.h>
#include <iostream>
#include <string.h>
using namespace std;
class A{
int age;
char *name;
char info[50];
public:
A(int p_age=0,char *p_name=NULL,char p_info[]=NULL)
{
cout<<"Constructor called"<<endl;
age=p_age;
int length1=strlen(p_name)+1;
int length2=strlen(p_info)+1;
strncpy(name,p_name,length1);
name[length1-1]='\0';
strncpy(info,p_info,length2);
info[length2-1]='\0';
}
void get()
{
cout<<"Enter the age";
cin>>age;
cout<<"Enter name & info";
gets(name);
gets(info);
}
void display()
{
cout<<age<<name<<info;
}
};
int main()
{
A obj(20,"Ename","Stud");
obj.display();
// A obj1("EEEE");//Line3
A obj2; //Line 4
obj2.get();
obj2.display();
}
A obj1("EEEE") is an error because the first parameter to your constructor is declared as an int p_age and the compiler cannot automatically cast "EEEE" into an int. Trying to initialize obj2 causes an error because you have provided no parameter in the call, so the default values are used, and when the line int length1=strlen(p_name)+1; is executed, strlen() crashes from accessing memory from p_name, which is NULL.
name is not allocated.
...
int length1=strlen(p_name)+1;
int length2=strlen(p_info)+1;
name = new char[length1]; // add this line
strncpy(name,p_name,length1);
name[length1-1]='\0';
strncpy(info,p_info,length2);
info[length2-1]='\0';
...
Your first argument in constructor is int and you are trying to pass const char*.
The default initialization for your p_name is NULL and strlen of null gives segmentation fault
In the declaration
A obj2
you do not provide the p_name and p_info arguments, so they are defaulted to NULL. Then in the constructor you call
strlen(p_name)
on p_name which is NULL. This is not allowed.
Let C++ help you.
class A{
int age;
std::string name;
std::string info;
public:
explicit A(int p_age = 0, const std::string& p_name = "", const std::string& p_info = "")
: age(p_age)
, name(p_name)
, info(p_info)
{
}
};
I'm having trouble declaring and initializing a char array. It always displays random characters. I created a smaller bit of code to show what I'm trying in my larger program:
class test
{
private:
char name[40];
int x;
public:
test();
void display()
{
std::cout<<name<<std::endl;
std::cin>>x;
}
};
test::test()
{
char name [] = "Standard";
}
int main()
{ test *test1 = new test;
test1->display();
}
And sorry if my formatting is bad, I can barely figure out this website let alone how to fix my code :(
If there are no particular reasons to not use std::string, do use std::string.
But if you really need to initialize that character array member, then:
#include <assert.h>
#include <iostream>
#include <string.h>
using namespace std;
class test
{
private:
char name[40];
int x;
public:
test();
void display() const
{
std::cout<<name<<std::endl;
}
};
test::test()
{
static char const nameData[] = "Standard";
assert( strlen( nameData ) < sizeof( name ) );
strcpy( name, nameData );
}
int main()
{
test().display();
}
Your constructor is not setting the member variable name, it's declaring a local variable. Once the local variable goes out of scope at the end of the constructor, it disappears. Meanwhile the member variable still isn't initialized and is filled with random garbage.
If you're going to use old-fashioned character arrays you'll also need to use an old-fashioned function like strcpy to copy into the member variable. If all you want to do is set it to an empty string you can initialize it with name[0] = 0.
Since you are using C++, I suggest using strings instead of char arrays. Otherwise you'd need to employ strcpy (or friends).
Also, you forgot to delete the test1 instance.
#include <iostream>
#include <string>
class test
{
private:
std::string name;
int x;
public:
test();
void display()
{
std::cout<<name<<std::endl;
}
};
test::test()
{
name = "Standard";
}
int main()
{
test test1;
test1.display();
std::cin>>x;
}
Considering you tagged the question as C++, you should use std::string:
#include <string>
class test
{
private:
std::string name;
int x;
public:
test();
void display()
{
std::cout<<name<<std::endl;
std::cin>>x;
}
};
test::test() : name("Standard")
{
}
c++11 actually provides two ways of doing this. You can default the member on it's declaration line or you can use the constructor initialization list.
Example of declaration line initialization:
class test1 {
char name[40] = "Standard";
public:
void display() { cout << name << endl; }
};
Example of constructor initialization:
class test2 {
char name[40];
public:
test2() : name("Standard") {};
void display() { cout << name << endl; }
};
You can see a live example of both of these here: http://ideone.com/zC8We9
My personal preference is to use the declaration line initialization because:
Where no other variables must be constructed this allows the generated default constructor to be used
Where multiple constructors are required this allows the variable to be initialized in only one place rather than in all the constructor initialization lists
Having said all this, using a char[] may be considered damaging as the generated default assignment operator, and copy/move constructors won't work. This can be solved by:
Making the member const
Using a char* (this won't work if the member will hold anything but a literal string)
In the general case std::string should be preferred