Can we initialize object with double quotation - c++

Is it possible to do something like
Class obj="";
Can use "" to initialize an object? I saw this in an interview, and the interviewer mentioned it is valid.
Update:
Thanks for the answers here. For the benefit of future readers, I did some search, this is called copy constructor. Some links like
copy constructor parameters
could be useful.

Yes, it really is valid. Here is an example code where it works:
#include <iostream>
#include <string>
using namespace std;
class Class {
private:
string data;
public:
Class (const char* foo) {
data = foo;
}
};
int main()
{
Class foo="bar";
return 0;
}

Related

C++ use iostream inside class [duplicate]

This question already has an answer here:
Does not name a type
(1 answer)
Closed 2 years ago.
The community reviewed whether to reopen this question 1 year ago and left it closed:
Original close reason(s) were not resolved
I'm using iostream and map. When I try to set the functions, they throw an error.
My code:
#include "string"
#include "iostream"
#include "map"
using namespace std;
class myClass {
map<string, string> Map;
Map["Ziv"] = "Sion";
cout << Map["Ziv"];
};
My error:
error: 'Map' does not name a type
error: 'cout' does not name a type
Why I can't use iostream and cout?
Why I can't use iostream and cout?
Because a class cannot (directly) contain expression statements. It can contain only member declarations.
Expression statements can only be within functions. This would be correct for example:
class main {
map<string, string> Map;
void example_function() {
Map["Ziv"] = "Sion";
cout << Map["Ziv"];
}
};
you can't have a C++ progran without the main function so please create int main(){}. And change the double quotes in the #include directives to angle brackets like below:
#include <string>
#include <iostream>
#include <map>
using namespace std;
class myClass {
public:
int myFunc();
};
myClass :: int myFunc(){
map<string, string> Map;
Map["Ziv"] = "Sion";
cout << Map["Ziv"];
}
int main(){
myClass myclass;
myclass.myFunc();
return 0;
}
Please consider i am a beginner and forgive my mistakes if any.
In object oriented languages, like C++, you can't write expressions/statements in a class. You may want to use a function. Example:
#include<iostream>
using std::cout;
class Example {
public:
void sayHello() {
cout << "Hello!";
}
}
int main() {
new Example().sayHello(); // Prints Hello!
}
You have to enter the cout in a function, inside the class you can't execute functions, you just can describe them or variables / objects.
Class is an Entity which contains related data members and the operations to modify or access those data members. No expression can be executed within the class. It does not make an sense to do something that you can not access. Because the only way to access and modify something are operations.
Yes in case if you want to print something when the class object is created, you can do that in Constructor. May be this is what you want to do:
#include <map>
#include <iostream>
#include <string>
class myClass {
private:
std::map<std::string, std::string> Map;
public:
myClass(const std::string& key, const std::string& value){
Map[key] = value;
std::cout << value;
}
};
int main(){
myClass cls("Ziv", "Sion");
}

Can we dynamically insert operations to our function?

In this thread link, concerns the discussion on real example of using the strategy design pattern. The second answer which shows an example of dynamically inserting rules to whether approve/decline the assignment of products to people with the RuleAgent. This set of rules is invoked using the function IsApproved.
The example shows what if we wanted to add two more rules, like an intern rule and overtime rule. My question relates to how do we ensure that our polymorphic call to IsApproved would call ALL the added rules. The question has also been asked in the comment to that answer but no replies.
Could you please comment on how to do this on C++ and/or (if possible) Fortran.
This example sidesteps polymorphism, where the agent is a vector of function pointers that can be dynamically added to and removed from :
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
class Person
{
public:
int _timesheet = 50;
std::string _title = "Intern";
};
class Assignment
{
public:
Person _person;
};
namespace OvertimeRule
{
bool IsApproved(Assignment const& assignment)
{
return assignment._person._timesheet >= 40;
}
}
namespace InternRule
{
bool IsApproved(Assignment const& assignment)
{
return assignment._person._title == "Intern";
}
}
int main()
{
Assignment testAssignment;
std::vector<bool(*)(Assignment const&)> assignmentAgent;
assignmentAgent.push_back(&OvertimeRule::IsApproved);
assignmentAgent.push_back(&InternRule::IsApproved);
bool const testSuccess = std::all_of(assignmentAgent.begin(), assignmentAgent.end(),
[&testAssignment] (auto const& Func)
{
return Func(testAssignment);
});
if(testSuccess)
{
std::cout << "Requirements Met!";
}
else
{
std::cout << "Requirements Not Met!";
}
}

How can I declare a struct?

I am currently learning C++ and trying to understand the usage of structs.
in C++. As far as I'm aware, if you want to define a function after the main() function, you have to declare it beforehand, like in this function (Please tell me if I'm wrong with it):
#include "stdafx.h"
#include <iostream>
#include <string>
void printText(std::string); // <-- DECLARATION
int main()
{
std::string text = "This text gets printed.";
printText(text);
}
void printText(std::string text)
{
std::cout << text << std::endl;
}
My question now is if there is a way to do the same with structs. I don't want having to always define a struct before the main() function, just because I prefer it like that. However, I get an error when I try doing it like that:
//THIS program DOESN'T work.
#include "stdafx.h"
#include <iostream>
#include <string>
struct Products {std::string}; // <-- MY declaration which DOESN'T work
int main()
{
Products products;
products.product = "Apple";
std::cout << products.product << std::endl;
}
struct Products
{
std::string product;
};
When I delete the decleration and instead define the struct before the main function, the program works so I assume I'm somehow wrong with the decleration:
//THIS program DOES work
#include "stdafx.h"
#include <iostream>
#include <string>
struct Products
{
std::string product;
};
int main()
{
Products products;
products.product = "Apple";
std::cout << products.product << std::endl;
}
Could someone tell me if there is some way to declare a struct like that? Bear with me if I have any major mistake in the code, I'm just a beginner.
Thanks in advance!
You can pre-declare (forward-declare) a class type in C++.
struct Products;
However, a class type declared in this way is incomplete. Incomplete types can only be used in a number of very limited ways. You will be able to declare pointers or references to such type, you will be able to mention it in non-defining function declarations etc., but you will not be able to define objects of such incomplete type or access their members.
If you want to define objects of class Products or access members of class Products, you have no other choice but to fully define the class before such use.
In your case you are defining an object of type Products in main as well as accessing members of class Products there. This means that you have to completely define Products before main.
In your particular case a forward declaration wont help, because a forward declaration only allows you to use pointers or references, as e.g. in
struct foo;
foo* bar(foo f*) { return f;}
struct foo { int x; }
However,
struct Products {std::string};
is not a declaration, but if you want an ill-formed declaration and definition.
The correct forward declaration would be:
struct Products;

C++ How to create a std::unique_ptr from a class that takes parameters on constructor

I need to create a std::unique_ptr from a class that has a constructor that takes one parameter. I can´t find references on how to do it. Here is the code example that cannot compile:
#include <iostream>
#include <string>
#include <sstream>
#include <memory>
class MyClass {
public:
MyClass(std::string name);
virtual ~MyClass();
private:
std::string myName;
};
MyClass::MyClass(std::string name) : myName(name) {}
MyClass::~MyClass() {}
class OtherClass {
public:
OtherClass();
virtual ~OtherClass();
void MyFunction(std::string data);
std::unique_ptr<MyClass> theClassPtr;
};
OtherClass::OtherClass() {}
OtherClass::~OtherClass() {}
void OtherClass::MyFunction(std::string data)
{
std::unique_ptr<MyClass> test(data); <---------- PROBLEM HERE!
theClassPtr = std::move(test);
}
int main()
{
OtherClass test;
test.MyFunction("This is a test");
}
The errors are related to the way I´m initializing the std::unique_ptr, pointed out in my code.
The original code and the errors can be found here.
Thanks for helping me to solve that.
You can do:
std::unique_ptr<MyClass> test(new MyClass(data));
Or if you have C++14
auto test = std::make_unique<MyClass>(data);
But:
In the provided example there is no need to create a temporary variable, you can just use the reset method of the class member:
theClassPtr.reset(new MyClass(data));
#include <memory>
...
int main()
{
std::string testString{ "Testing 1...2....3" };
auto test = std::make_unique<MyClass>( testString );
return 0;
}
It's basically an oversight. You need this:
#include <memory>
namespace std
{
template <class T, class... Args>
std::unique_ptr <T> make_unique (Args&&... args)
{
return std::unique_ptr <T> (new T (std::forward <Args> (args)...));
}
}
C++14 comes with std::make_unique. It was omitted from C++11.
Writing it yourself is easy:
namespace notstd{
template<class T,class...Args>
std::unique_ptr<T> make_unique(Args&&...args){
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
}
now use it like this:
auto foo = notstd::make_unique<MyClass>(string);
will make your unique ptr for you.
This pattern has a few advantages. First, it removes a new that is not paired with a delete from "user code", which makes me happy.
Second, if you call a function that takes 2 unque ptrs, ths above can avoid leaks in case of exceptions being thrown.
We put this in notstd as injecting new functions into std is illegal inder the standard (no diagnostic required).

C++ compile time error: expected identifier before numeric constant

I have read other similar posts but I just don't understand what I've done wrong. I think my declaration of the vectors is correct. I even tried to declare without size but even that isn't working.What is wrong??
My code is:
#include <vector>
#include <string>
#include <sstream>
#include <fstream>
#include <cmath>
using namespace std;
vector<string> v2(5, "null");
vector< vector<string> > v2d2(20,v2);
class Attribute //attribute and entropy calculation
{
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
public:
Attribute(){}
int total,T,F;
};
int main()
{
Attribute attributes;
return 0;
}
You cannot do this:
vector<string> name(5); //error in these 2 lines
vector<int> val(5,0);
in a class outside of a method.
You can initialize the data members at the point of declaration, but not with () brackets:
class Foo {
vector<string> name = vector<string>(5);
vector<int> val{vector<int>(5,0)};
};
Before C++11, you need to declare them first, then initialize them e.g in a contructor
class Foo {
vector<string> name;
vector<int> val;
public:
Foo() : name(5), val(5,0) {}
};
Initializations with (...) in the class body is not allowed. Use {..} or = .... Unfortunately since the respective constructor is explicit and vector has an initializer list constructor, you need a functional cast to call the wanted constructor
vector<string> name = decltype(name)(5);
vector<int> val = decltype(val)(5,0);
As an alternative you can use constructor initializer lists
Attribute():name(5), val(5, 0) {}
Since your compiler probably doesn't support all of C++11 yet, which supports similar syntax, you're getting these errors because you have to initialize your class members in constructors:
Attribute() : name(5),val(5,0) {}