Create objects in conditional c++ statements
I don't know if I understood your question correctly but can't you just declare report before the if/else block and then initialize inside it?
Report header;
if (...) {
header = Report();
else
header = Report(name,company);
Or in a shorter way:
Report header; // calls default constructor
if (shouldInitializeWithParams) {
header = Report(name,company);
}
Of course this requires you to have the empty constructor defined.
How can i have an if statement when creating an object in c#?
You can just do this afterwards if this is an object data assignment.
var modelObj = new TestModel
{
Id = id,
Description = obj.Description
}
if (status == 1)
{
modelObj.Service = obj.Url,
modelObj.Username = obj.ServiceUsername,
}
else
{
modelObj.Password = obj.Password,
modelObj.Token = obj.Token,
modelObj.FirstName = obj.FirstName
}
Otherwise best bet is to use a class constructor instead of inline initialization.
How can I conditionally instantiate an object?
You can use an IIILE (immediately invoked initializing lambda expression):
auto object = [&] {
if (cond) {
doSomeStuff();
auto object = getObject();
doMoreStuff();
return object;
} else {
doSomeOtherStuff();
auto object = getDifferentObject();
doEvenMoreStuff();
return object;
}
}(); // note that the lambda must be called
use(object);
This will work even if Type
is not default-constructible.
Here's a demo.
Is there a way to declare objects within a conditional statement?
In your case, because you want to accomplish polymorphism, you should go for pointers and references. Why? I would highly recommend this beautiful answer. Why doesn't polymorphism work without pointers/references?
So, should you go for a raw pointer, something like Player *
?
In almost all scenarios, you should never ever go for raw pointers and especially, when it points to dynamic memory. Simply because any programming error or an exception might lead to delete
getting skipped.
Therefore, I would highly recommend you to go for smart pointers introduced in C++11 like unique_ptr
and shared_ptr
which follow RAII pattern and guarantee deinitialization.
Here is an example of usage of unique_ptr
in your case.
#include <memory>
using PlayerPtr = std::unique_ptr<Player>;
using KnightPtr = std::unique_ptr<Knight>;
using WizardPtr = std::unique_ptr<Wizard>;
int main()
{
...
PlayerPtr playerPtr = nullptr;
switch (input) {
case 1: {
playerPtr = KnightPtr(new Knight);
}
break;
case 2: {
playerPtr = WizardPtr(new Wizard);
}
break;
}
// use playerPtr outside.
}
Edit:
As rightly pointed out by HTNW, you must go for std::make_unique
instead of using new
. But remember, that is a C++14 concept. You must have compiler support for it.
Can we declare a object inside the if-else statement?
The simple answer is: Yes, you can declare objects inside if
and else
blocks, but they will be destroyed while leaving this blocks. In fact, after the if
block there is no obj
anymore.
Your idea to have different data types represented by a single object, depending on other runtime variables will not work in c++. C++ has a strong type system which makes your code idea impossible. That can be done on languages like python, but not at all by c++.
If you have the same algorithm, which should be used for different data types, you can play with templates. But this will still generate the complete code multiple times, a single instance per used data type.
From C++17 you can use std::variant
to have a container, which can contain different data types during runtime. But that comes with the cost, that there is an additional value ( tag ), which tells the rest of the code which data type is currently stored in the variant itself. On every access the compiler has to generate something like if ( data == int ) then ...
In detail it will be handled a bit different ( jumptable for different methods to call ). variant
can also be used from other libraries like boost before C++17.
Related Topics
Are Destructors Run When Calling Exit()
Std::Istream_Iterator<> with Copy_N() and Friends
Lambda Capture by Value Mutable Doesn't Work with Const &
G++ Ld: Symbol(S) Not Found for Architecture X86_64
Linux Executable Can't Find Shared Library in Same Folder
Absence of Typeof Operator in C++03
Rvalue Reference Parameters and Template Functions
How to Compile: Unrecognized Relocation
Could Not Load Spatialite Extension in Qsqlite ( Qt 5.9)
Static Initialization and Destruction of a Static Library's Globals Not Happening with G++
How to Compile a C++ Code in Gcc (G++) to See The Name Mangling on Overloaded Functions
What's the Difference Between C and C++
Cannot Open Windows.H in Microsoft Visual Studio
C++ What Happens When in One Thread Write and in Second Read the Same Object? (Is It Safe)
Remote Debugging C++ Application with Eclipse Gui
How to Create a N Way Cartesian Product of Type Lists in C++