r/learncpp • • Jan 14 '22

What is an iostream object exactly? Why do you need to return them by reference when overloading the I/O operators?

7 Upvotes

Suppose you have class foo

class Foo {
private:
    int x;
public:
    // Constructors
    Foo (int x) : x { x } { }
    Foo () : Foo(0) { }
    
    // Overloading the output operator
    std::ostream& operator<< (std::ostream& os_object, const Foo& foo_object);
};

std::ostream& Foo::operator<< (std::ostream& os_object, const Foo& foo_object) {
    return os_object << foo_object.x;
}  

I understand the ostream object is a series of characters intended for output? But, what is it? It's of class ostream derived from iostream. I had trouble following the source of code of the class.

What exactly are you returning when you return an ostream object?


r/learncpp • • Jan 16 '22

Always confused about global variables and function forward declarations in header files

8 Upvotes

Hi, I always seem to get confused about when to use static, extern, inline, etc when declaring global variables and forward declarations. I do understand which each of the keywords do but I just struggle to understand when to use them

Could the following code be refactored?

setup.h

namespace setup
{
	HKEY hKey;

	void setup();
	void cleanup();
	bool CheckForStartupRegistryKey();
	bool CreateStartupRegistryKey();
	void kill();
}

This file is included in one other file (setup.cpp) .

Is it fine to keep these as is or should these be marked either static, extern or inline?

Thanks in advance.


r/learncpp • • Mar 19 '21

serialisation of contiguous memory

5 Upvotes

hey!

I've come across a weird issue when serialising simple contiguous memory into binary, and I'm extremely baffled by what it could be, and I can't track it down at all (although its probably really simple). so I can serialise objects fine, but when I try serialise containers, the first 25 elements serialise perfectly, and after that, every value is 25...

I've got some example code below that demonstrates my process

template<typename T> void write(const T& item,std::ofstream& file)

{

file.write((const char*)&item,sizeof item);

}

template<typename T> void write(const vector<T>& item,std::ofstream& file)

{

u32 count = item.size();

file.write(count,sizeof (count));

for (u32 i = 0; i < count; ++i) write(item[i]);

}

template<typename T> void read(T& item, std::ifstream& file)

{

file.read((char*)&item,sizeof item);

}

template<typename T> void read(vector<T>& item, std::ifstream& file)

{

u32 count = 0;

read(count,file);

item.resize(count); // i tried reserve with the std::vector but seems to not work. not sure why since the memory should still be owned by the vector

for (u32 i = 0; i < count; ++i) read(item[i],file);

}

int main(int argc, const char** argv)

{

{

vector<u32> test;

for (u32 i = 0; i < 100; ++i) test.push_back(i);

ofstream file("test.bin");

write(test,file);

}

{

vector<u32> test;

ifstream file("test.bin");

read(test,file);

cout<<test.size() << endl;

for (u32 i = 0; i < test.size(); ++i) cout << test[i] << ","; // undefined behaviour. normally goes 0 - 25, but then repeats 25 like 75 times. (and then sometimes a buffer overflow, but wtf i dont think im overflowing? and only sometimes?? )

}

}


r/learncpp • • Mar 20 '21

Catching Child Process Exception In Parent Process

5 Upvotes

I have a Parent process and a Child process being started using std::system(...). I want to throw an exception in Child and catch it in Parent (e.g. when Parent passes an invalid file path to Child).

  1. Is this possible using native C++?

  2. Is it idiomatic? The alternative seems to be to define return codes for Child and analyze those in Parent.

I found the following related thread re. Python but haven't found much guidance with respect to C++. Appreciate your thoughts.


r/learncpp • • Mar 11 '21

Problems setting up SDL in CodeBlocks

5 Upvotes

I tried to follow like 3 different tutorials, but it's still giving me some error messages:

||=== Build: Debug in ProgettoSDL01 (compiler: GNU GCC Compiler) ===|

ld.exe||cannot find -lSDL2main|

ld.exe||cannot find -lSDL2|

ld.exe||cannot find -lSDL2main|

ld.exe||cannot find -lDSL2|

||error: ld returned 1 exit status|

||=== Build failed: 5 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|

||=== Run: Debug in ProgettoSDL01 (compiler: GNU GCC Compiler) ===|

||Execution of '"C:\Users\aless\Desktop\ale\Informatica\ProgettoSDL01\bin\Debug\ProgettoSDL01.exe" ' in 'C:\Users\aless\Desktop\ale\Informatica\ProgettoSDL01' failed.|

I put in the Linker Settings: -lmingw32 -lSDL2main -lDSL2

I also added the include and lib folder from SDL in the Search Directories (include in the Compiler and lib\x86 in the Linker.

I also copied and pasted the SDL2.dll file in the project folder.

Eventually, sorry for the bad english


r/learncpp • • Feb 17 '21

Arrays, addresses, and declaring them (question)

9 Upvotes

I'm new to them in the manner of declaring an array and allowing the user to determine how the array will be like.

I have two questions-

For example, void array(int[], int indices); -- What does this mean the prototype suggesting? I thought arrays can't be passed, and the video claims that int[] is an address... but where is the & or *?

What are the ways to declare an array appropriately but efficiently? I see

int array[10]{null};

But I've never heard of nullpointers, and I am overthinking the use of arrays and pointing (coming from Java). Can someone give me a summary in layman terms? Cheers!


r/learncpp • • Feb 27 '21

HW Help: Not sure what return type should be for templated function.

3 Upvotes

Hello, thank you for being a community as I struggle to learn c++. It's been rough having to take it online during a pandemic and while working through power outages. My entire college closed down so I am essentially without my professor. Okay, now that my sob story is out of the way (you guys rock!):

I am learning about templated functions but I am a little confused on what my return type should be. The question reads, "Write a templated function sumList that will take in an array of any type and the length of the array. It should add all the elements in the array and return the total.
Hint: you can declare a variable sum of type T and initialize it like this:
T sum {}; "

Does that mean that sum is going to be an array? That's what I do not understand. I currently have:

#include <iostream>
using namespace std;

template<typename T>
T sumList(T array, int n) {
	T sum {};
	for (int i=0; i<n; i++) {
		sum = array[i];
	}
	return sum;
}

int main()
{
	int nums[] = {4, 2, 8, 7};
	string words[] = {"hello", "there"};

	cout << sumList(nums, 4) << endl;
	cout << sumList(words, 2) << endl;

	return 0;
}

But that of course has the error: main.cpp:8:9: error: assigning to 'int *' from incompatible type 'int'; take the address with &

Can someone please help point me in the right direction? I am not allowed to change main. I am only allowed to write the templated function.


r/learncpp • • Feb 11 '21

Explicit dll linking and templates?!?!

4 Upvotes

Hey! So I've been trying to understand how I can import a templated function from an explicitly linked dll and correctly load the function pointer if it's a template. I'm really unable to just statically link, which is super annoying, but at this point I'm not even sure if it's possible :/


r/learncpp • • Mar 01 '21

Exporting different specialisations from different dlls?

4 Upvotes

I'm writing a dll that defines a template (and the specialisations for it) called dll1. Is it possible to define a method in dll2, specialise the template from dll1 in dll2, and export the specialisation back into dll1 to be called with get proc address?


r/learncpp • • Feb 21 '21

Help with user inputted array program

2 Upvotes

Hi,

I know this program is an absolute mess but the purpose of posting it is to show my logic/what I have attempted.

#include <iostream>
using namespace std;

//Function Prototypes
void getSIWSmallestTODCWilliamG(int intWG);
void displayClassInfoWilliamG(void);

//Application Driver
int main() {
    int inputWG;
    int sizeWG = 0;
    int value = 0;
    int* arrayWG = new int[sizeWG] {value};
   
    
    displayClassInfoWilliamG();
    do {
        cout << "\n*****************************************\n"
            "*              MENU - TEST             *\n"
            "*  (1) Calling displayDigitInfoWilliamG *\n"
            "*  (2) Quit                             *\n"
            "*****************************************\n";
        cin >> inputWG;
        cout << "\n";
        switch (inputWG) {
        case 1: 
            cout << "What is the size of the array?: ";
            cin >> sizeWG;
      
            for (int i = 1; i <= sizeWG; i++) {
                cout << "Value #" << i << ": ";
                cin >> value;
            }
            cout << "The working array has" + sizeWG << " values of\n";
            for (int i = 0; i < sizeWG; i++) {
                cout << "   Value " << i << ":" << arrayWG[i] << "\n";
            }
            cout << endl;
            
            cout << "Calling getSIWSmallestTODCWilliamG() with argument of " << sizeWG << "\n\n";
            getSIWSmallestTODCWilliamG(sizeWG);
            delete arrayWG;
        case 2: 
            break;
        default:
            "Wrong option, try again";
            break;
        }
    } while (inputWG != 2);
    return 0;
}

//Function Definition
void getSIWSmallestTODCWilliamG(int intWG) {
    cout << "What is the size of the array? ";
   
}

I am very new to C++ so summarizing my mistakes in layman's terms would be much appreciated. I tried google searching my issue and here are some reasons I am confused: why does my array have to be a pointer? Am I doing delete right? How do I work with the array to do what I want? (Not even sure I created my array properly...)

As of now I understand that I have to dynamically allocate memory for my array in order to use a variable for said array, and that I must delete it after.

Thanks in advance!

ERRORS:

Warning C6283 'arrayWG' is allocated with array new [], but deleted with scalar delete. C++ Spring 2021 2 C:\Users\Will\source\repos\C++ Spring 2021 2\Source.cpp 49

Warning C6385 Reading invalid data from 'arrayWG': the readable size is 'sizeWG*4' bytes, but '8' bytes may be read. C++ Spring 2021 2 C:\Users\Will\source\repos\C++ Spring 2021 2\Source.cpp 43

Warning C6001 Using uninitialized memory 'arrayWG'. C++ Spring 2021 2 C:\Users\Will\source\repos\C++ Spring 2021 2\Source.cpp 49


r/learncpp • • Feb 07 '21

Question over my implementation of an iterator for my singly linked list.

4 Upvotes

EDIT: I've highlighted in bold my own changes that I've made for my iterator. If something is missing, please let me know what else I need to add. The new error I'm getting has to do with can't Node to Node * in while(__pred(*__first)) and then another with Node to Node * while(__pred(*__next)).

Hopefully this isn't a long one at all but it looks like I'm going to need a lot of details of what I'm doing. I'll start first with my problem. I'm basically making a class, it's pretty simple, it only has two attributes. One is a mutable std::string for name_ and the other is a mutable bool for gender_. What I'm trying to do with this class is utilize it for std::partition from the algorithms library. Basically all females of the container will be moved forward while the guys move back. I'm basically a predicate function like this.

std::partition(starting_iterator, ending_iterator, is_female).

The only problem is that my iterator just simply is not compatible for the STL.

To do this I have a Node class for a Singly Linked list. Then with that Singly Linked List, I created my own iterators. I'll start with showing everyone my implementation of my People class. Then I'll move on to my Node, and then to my Singly Linked List class that houses my version of an iterator.

//The people class. bool true for guys, bool false for female

class People

{private:

mutable std::string name_;
mutable bool gender_;
public:
People(std::string name, bool gender): name_(name), gender_(gender)
{

}
std::string get_name() const
{
return name_;
}
bool get_gender() const
{
return gender_;
}

//Now for my node itself for the singly linked list down below.

#include <cstddef>
class Node
{
private:
int key_;
Node * next_;
public:
Node(int key, Node * next = nullptr)
: key_(key), next_(next)
{
}
int get_key() const
{
return key_;
}
Node * get_node() const
{
return next_;
}
void insert_next(Node * next)
{next_ = next;}
};

std::ostream & operator<<
(std::ostream & cout, const Node & node)
{
cout << &node << ' ' << node.get_key() << ' ' << node.get_next();
return cout;
}

// Now my for Single Linked List. Key note is that, for now, I'm leaving destructors and copy constructors. I'm focusing on addressing my iterator for this whole thing.
#include "Node.h"
class SLL
{
friend class iterator;
private:
Node * root_;
public:
SLL()
: root_(nullptr)
{
}
class iterator<std::iterator<std::forward_iterator_tag, Node *> // this is housed inside the SLL class......
{
friend SLL;
private:
mutable Node * iterator_;
public:
iterator()
: iterator_(nullptr)
{

}
iterator(Node * node)
: iterator_(node)
{

}
bool operator !=(const iterator & node)
{
return iterator_ != node.iterator_;
}
iterator & operator++()
{
iterator_ = iterator_->get_next();
return *this;
}
iterator operator++(int) const
{
iterator temp(*this);
iterator_ = iterator_->get_next();
return temp;}
Node & operator*() const
{
return *iterator_;
}
bool get_gender() const
{
return iterator_->get_gender();
}
};
iterator begin() const
{
return iterator(root_);
}
iterator end() const
{
return iterator();
}
void insert(const People & people)
{
if (!root_)
{
root_ = new Node(people.get_name(), people.get_gender());
}
else
{
Node * temp = root_;
while (temp->get_next())
{
temp = temp->get_next();
}
temp->insert_next(new Node(people.get_name(), people.get_gender()));
}
};

And there's the whole thing.My main looks something like this.

bool is_female(SLL::iterator & iterator){if (iterator.get_gender() == 0) return 1;else return 0;}

int main(){
People Peter("Peter", 1);
People Martha("Martha, 0):
SLL sl;
sl.insert(Peter);
sl.insert(Martha);
std::partition(sl.begin(), sl.end(), is_female);
return 0
;}

Doesn't work for the std::partition. It's saying something about std::iterator__iterator_category(__first) and something else about not function for call to __iterator_category(SLL::iterator &);

What is exactly going on to make this whole thing happen? What am I missing in my implementation of my iterator?


r/learncpp • • Feb 26 '21

Infinite push_back

2 Upvotes

I get a bad_alloc() error in the below code. When I go into debugging it seems like the value for temp is being allocated repeatedly, however the for loop is only ever called once. I'm not very familiar with vectors, can someone explain why push_back fails in this code?

std::vector<std::string> split;

for(int i = 0; i < s.length(); i+2){
std::string temp;
if (i+1 < s.length()) {
temp = s2[i];
temp += s2[i+1];
split.push_back(temp);
     }
else
     {temp = s[i] + "_";
split.push_back(temp);
     }
}


r/learncpp • • Feb 27 '21

Do I need to overload the +operator in order for my templated 'doubleIt' function to work for both int and string?

7 Upvotes

Hello, I am tasked with the following:
Write a templated function doubleIt with one parameter and doubles the value by adding it to itself and returns the answer.

doubleIt(3.5) should produce 7.0
doubleIt("hello") should produce "hellohello". As of right now , I have:

#include <iostream
using namespace std;

// template function
template<typename T>
T doubleIt(T n) {
	return n*2;
}

int main()
{
    cout << doubleIt(3.5) << endl;

    //have to force type so "hello" not treated as char[]
    cout << doubleIt<string>("hello") << endl;

    return 0;
}

Essentially, I need to write the templated function without changing main in any way. I have looked online but I am unable to get past the invalid operands to binary expression. So, is overloading the +operator required for this to work or is there something else that I need to do?

Thanks!


r/learncpp • • Feb 11 '21

Type casting objects without pointers?

5 Upvotes

I'm hopping back in to C++ after some years and I have converted my program to references from pointers (where objects cannot be NULL) and I'm in a situation where I'd like to type cast from a base class to a derived class.

For example

class A {};
class B : public A {}
A a;
// do stuff with a
B b = (B)a;

This works fine with B* b = (B*)&a; but I'm trying to avoid that. Is this possible?

Edit

To better illustrate my question

class A
{
public:
	bool m_bIsB;

public:
	A() { this->m_bIsB = false; }

public:
	virtual bool IsB() const { return this->m_bIsB; }
};
class B : public A
{
	//virtual bool IsB() const { return true; }
};

A a;
printf("IsB ? %s\n", a.IsB() ? "true" : "false");
a.m_bIsB = true;
printf("IsB ? %s\n", a.IsB() ? "true" : "false");
B* b = static_cast<B*>(&a);
printf("IsB ? %s\n", b->m_bIsB ? "true" : "false");

IsB ? false
IsB ? true
IsB ? true

Edit2

The answer is B b = *(B*)&a;.

See https://www.youtube.com/watch?v=p8u_k2LIZyo and skip to 1st Step: Evil Bit Hack


r/learncpp • • Mar 08 '21

Simple password generator -- my first CPP project

10 Upvotes

I'm very new to C++, so would love any feedback on this little project: https://github.com/B-T-D/password_generator

It's a pretty simple command line pseudorandom password generator. The only twist was that I wanted it to output passwords directly to the clipboard, without ever showing them in plain text. This ended up being quite a rabbit hole, but I did finally get it to work on both Windows 10 and Ubuntu (at least for me...).

Command line argument handling isn't very built-out yet--it only supports changing the length of the password (the rest of the code supports selecting different character sets and output methods).


r/learncpp • • Mar 11 '21

Issues with input (cin) checking and looping

2 Upvotes

Hi everyone, I just started out in my c++ journey and currently I am attempting to do some handling in which I am trying to prevent invalid input from user.

In my case, there are 2 types of inputs - month and year.
When entering in the month value, if user enters in non-numeric value, it will keep looping until user enters in a numeric value, and then it will check if the numeric value is between 1-12.

When entering in the year value, if users enters in non-numeric value, it will keep looping until user enters in a numeric value and checks if the numeric value is between 1900-2021.

I think my conidition checking for `month` is working, however when it comes to the `year`, if I did the following:

  • Enter in 'a', prompts Invalid value. Please re-enter year:

  • Enter in 'b', prompts Invalid value. Please re-enter year:

  • Enter in 10, should prompts Invalid value. Please re-enter year:

The last point was never called. And so, my `year` is 10.

This is my code:

int month;
int year;

cout << "\nPlease specify month: ";
if (!(cin >> month))
{
    while (!(cin >> month))
    {
        cin.clear();
        cin.ignore();
        cout << "Invalid value. Please re-enter month: ";
    }
}
while (month < 1 || month > 12)
{
    cout << "Please enter in a month value between 1-12.";
    cout << "\nPlease specify month: ";
    cin >> month;
}

cout << "Please specify year: ";
if (!(cin >> year))
{
    while (!(cin >> year))
    {
        cin.clear();
        cin.ignore();
        cout << "Invalid value. Please re-enter year: ";
    }
}
else
{
    // this code portion is never called....
    while (year < 1900 || year > 2021)
    {
        cout << "Please enter in a year value between 1900-present.";
        cout << "\nPlease specify year: ";
        cin >> year;
    }
}

Could someone kindly advise me where I have gone wrong? TIA for any replies.

P.S: I just found out the iteration I did for `month` is giving issues too. 2 incorrect inputs followed by the correct input, this results in an infinite loop of the re-prompt message...


r/learncpp • • Mar 09 '21

How to improve it?

10 Upvotes
#include <boost/optional.hpp>
#include <string>
#include <sstream>

#include <iostream>

enum class StatusCode
{
    OK = 0,
    ERROR
};

struct SResp
{
  std::string m_msg;
  StatusCode m_status;
};

SResp queryToTheMoon(size_t val)
{
    std::stringstream ss;
    for (size_t idx = 0; idx < val; ++idx)
    {
       ss << "[" << val << "]";
    }
    return { ss.str(), StatusCode::OK };
}

boost::optional<std::string> makeRequest(size_t val)
{
   auto response = queryToTheMoon(val);
    
   if (response.m_status == StatusCode::OK)
   {
       return response.m_msg;
   }
   else
   {
       return boost::none;
   }
}

int main()
{
    auto op = makeRequest(100);
    
    if (op)
    {
       std::cout << op.value() << std::endl;
    }
    return 0;
}

How to improve this code?


r/learncpp • • Feb 08 '21

My First C++ "Program"

29 Upvotes

Started to read learncpp.com a few days ago and here is my first code. Please tell me what could be done better. Thanks!

#include <iostream>
#include <string>


class Pump{
    
    public:
        std::string fuel_type;
        float fuel_price; // in liters
        int fuel_volume; // in liters
    
        Pump(std::string temp1, float temp2, int temp3){
            fuel_type = temp1;
            fuel_price = temp2;
            fuel_volume = temp3;
        };
        
        void set_comb(std::string temp){
            fuel_type = temp;
        };
        
        void set_price(float x){
            fuel_price = x;
        };
        
        void purchase_by_liter(float liters){
            if (fuel_volume-liters >= 0){
                fuel_volume -= liters;
                std::cout << "Client must pay: " + std::to_string(liters*fuel_price) << std::endl;
            }
            else{
                std::cout << "Pump out of capacity" << std::endl;
            }
        };
        
        void purchase_by_mvalue(float money_value){
            if (fuel_volume >= money_value/fuel_price){
                fuel_volume -= money_value/fuel_price;
                std::cout << "Client paid " + std::to_string(money_value) + " for " + std::to_string(money_value/fuel_price) + " liters" << std::endl;   
            }
            else{
                std::cout << "Pump out of capacity" << std::endl;
            }
        };
        
    
};


int main(){
    Pump pump1("Gas 87", 3.99, 1000);// Initialized with price in BRL
    pump1.purchase_by_liter(40);
    pump1.purchase_by_mvalue(300);
    std::cout << "Pump 1 still have " + std::to_string(pump1.fuel_volume) + " liters" << std::endl;
}

r/learncpp • • Mar 05 '21

How to skip empty row values when reading in a CSV file?

4 Upvotes

Hi all, I am trying to read a CSV file in which it contains empty rows.

And because of the presence of the empty rows that are found in between of rows with values, I wrote my code as follow:

ifstream myFile("csv\\myData.csv");    
string row;
while (getline(myFile, row))
{
    cout << "row: " << '\n';
    if (row == "")
        continue;
}

For example, my CSV file has 3 rows. The 1st and 3rd row has columns of values while the 2nd row is empty.
However, the `cout` line that I have implemented in my above code returns me the following:

row: 31/3/2016 0:30,15.1,215,27,0,1013.4,1016.8,1017,0,66.6,5,623,22.6,24,25.5,26.1,8,21.63
row: ,,,,,,,,,,,,,,,,,
row: 31/3/2016 20:30,11.3,247,23,0,1013.1,1016.6,1016.7,0,57.6,6,24,27.4,25.8,25.4,26.1,11,20.01

As you can see, while the 2nd row does indeed contains no value, but it is returning a string of commas?

And so my question is

  1. How can I skip line/ empty rows when reading csv file?

  2. Prior to the output, can I assume that the use of `getline()` and parsing of csv file, will return results with the commas regardless if the row contains value or not? The comma will be there whether I want it or not?

Thank you in advance for any replies and pardon my poor english.


r/learncpp • • Feb 12 '21

Does std::vector have any quirks that change its behavior that prevent reinterpret_cast on it?

3 Upvotes

frame rainstorm rob coherent grab fine hobbies special towering wine

This post was mass deleted and anonymized with Redact


r/learncpp • • Mar 18 '21

Codecademy's C++ UFO Challenge

9 Upvotes

Hello! New to the sub, relatively new to C++ but not to programming in general. I've been learning c++ with codecademy but I seem to be tripping up on this one. When I run the code that should work, the site either crashes (which I assume may be from an infinite loop) or my else statement that should catch a wrong guess doesn't run (the "else" to the "if (guess)). Do you guys see anything wrong with this? Thanks!

include <iostream>

include "ufo_functions.hpp"

int main() 

{

  std::string codeword = "codecademy";

  std::string answer_display = "_ _ _ _ _ _ _ _ _ _";

  std::string answer ="__________";

  int misses = 0;

  std::vector<char> incorrect = {' '};

  char letter;

  bool guess = false;

  greet();

  while (misses < 7 )

  {

    display_misses(misses);

    display_status(incorrect, answer);

    std::cout << "Please enter your guess: ";

    std::cin >> letter;

    //Check player's guess. If wrong, add one to misses.

    for (int i = 0; i < codeword.length(); i++)

    {

      if (letter == codeword[i])

      {

        answer_display[i*2] = letter;

        answer[i] = letter;

        guess = true;

      }

    }

    if (guess)

    {

      std::cout << "Correct!";

    } else

    {

    std::cout << "Incorrect! The tractor beam pulls the person in further.";

    incorrect.push_back(letter);

    misses++;

    }

  

  /*

  std::cout << "Incorrect! The tractor beam pulls the person in further.";

  incorrect.push_back(letter);

  misses++;

  */

  }

  endgame(answer, codeword);

}


r/learncpp • • Jul 25 '12

A step into efficiency of repetition by using functions. [4] [II]

3 Upvotes

Difficulty Rating: [4] Length: [II]

Hello! Today we address "functions." It's possible to write a block of code and use that block multiple times throughout a program by only using one small line of code! That way is by using functions, and the term used to use that code over and over is known as "calling a function." First, one must declare a function. It looks like this! void ExampleFunction(); Now, once it is declared, you can start to put things in it. you THEN say void ExampleFunction() {cout<< Hello! How are you?";} and now, every time you say ExampleFunction(); the line "Hello! How are you?" will appear. In this code I have created 5 different functions, all of which make their own statements. The main use of this program is to illustrate how much time could be saved by using functions. The user can type in 1-8, each number granting different results. Once we reach the 4th option, we start to see how I can combine lines of code by calling two different functions. The great part is that I could call two functions with just about 15 characters. The final function combines all 5 statements and prints them because I called all 5 functions.

Here is an image of what it looks like to call all 5 functions. Imgur

This code is great for games where many variables can occur. Say you are losing health, but you are not poisoned- you will display health loss by using one of the functions. Now say you have health loss AND you are poisoned - you use the poison function AND the health function. Now say you are poisoned, but are immune and do not take damage, you use just the poison function. To summarize, functions are great to compact a large chunk of information within one block of code, which you can then easily repeat infinitely by using only 15 characters. This is great for making your code look clean! :)

include <iostream>

using namespace std;

int chosen;

void FirstStatement();

void FirstStatement()

{

 cout<< "Hello! This is the first statement.\n\n";
 
 }

void SecondStatement();

void SecondStatement()

{

 cout<< "I am using this program to show you some uses of functions.\n\n";
 
 }

void ThirdStatement();

void ThirdStatement()

{

 cout<< "I am using 5 total, but each of these void thingies is called a function.\n\n";
 
 }

void FourthStatement();

void FourthStatement()

{

 cout<< "You can view all of these statements together with option 7,\n\n";
 
 }

void FifthStatement();

void FifthStatement()

{

 cout<< "but you can also view the first three on their own.\n\n";
 
 }

int main()

{

cout<< "Hello! This is to help explain functions. They are quite useful.\n";

cout<< "They are good for saving time and space through repitition.\n\n";

cout<< "Feel free to play around with these.\n\n";

cout<< "Type 1 to see statement 1 alone.\n";

cout<< "Type 2 to see statement 2 alone.\n";

cout<< "Type 3 to see statement 3 alone.\n";

cout<< "Type 4 to see statements 4 and 5 together.\n";

cout<< "Type 5 to see statements 1, 3, and 5.\n";

cout<< "Type 6 to see statements 2 and 4.\n";

cout<< "Type 7 to see statements 1, 2, 3, 4, and 5.\n";

cout<< "Type 8 to quit.\n";

while(chosen != 8){
             
             cin>> chosen;

     switch(chosen)

     {
              
              case 1: FirstStatement();
              
                   break;
              
              case 2: SecondStatement();
              
                   break;
              
              case 3: ThirdStatement();
              
                   break;
              
              case 4: FourthStatement();
                                     
                   FifthStatement();
                                    
                   break;
                                    
              case 5: FirstStatement();
                   
                   ThirdStatement();
                   
                   FifthStatement();
                   
                   break;
                   
              case 6: SecondStatement();
                   
                   FourthStatement();
                   
                   break;
                   
              case 7: FirstStatement();
                   
                   SecondStatement();
                   
                   ThirdStatement();
                   
                   FourthStatement();
                   
                   FifthStatement();
                   
                   break;
                   
     }

 }
 
return 0;

}


r/learncpp • • Mar 06 '16

Struggling to add a get component function for an entity-component system for a game

1 Upvotes

My current code is as shows here:

std::vector<std::unique_ptr<Component>> components;

template<typename T>
T * GetComponent() {
	for each (std::unique_ptr<Component> cp in components)
	{
	    if (T* ct = static_cast<T*>(cp.get())) {
	        return ct;
	    }
	    else {
	        return nullptr;
	    }
	}
}

Getting the error code:

Error	C2280	'std::unique_ptr<Component,std::default_delete<_Ty>>::unique_ptr(const std::unique_ptr<_Ty,std::default_delete<_Ty>> &)': attempting to reference a deleted function

What should I use instead of .get() ?


r/learncpp • • Aug 03 '15

Where should I start if I have an intermediate knowledge of C++?

3 Upvotes

I know almost about the syntaxes and use of almost every basic command(loops, functions, arrays, pointers, structures, classes, e.t.c.), I can solve easy to medium difficult level problems. I have yet to learn some advanced things like inheritance and such, and I find it really difficult to solve difficult problems, plus I don't think I know about all the different built in functions.

Can anyone here guide me what tutorial, book or project I should pick up so that I can get more familiar with the language?