C++ ::  how To Correctly Initialize Instances Of A Class

Feb 1, 2015

I am struggling to understand what the correct way to initialize instances of a class for object orient programming is.

If I am not mistaken, there are 2 methods to initialize an instance "instance_name" of CLASS1 by calling the constructor:

(1) CLASS1 instance_name(argument);
(2) CLASS1 instance_name=CLASS1(argument);

As it turns out, I cannot use method (1) when I try to initialize a private instance inside another class. But I can use it in the main() code. I hope the code below will explain what I mean. Why only method (2) will work inside another class? Or is there another fundamental mistake I am making?

(BTW: I used CodeBlocks 13.12 with GNU GCC compiler for this example)

#include <iostream>
using namespace std;
class CLASS1{

[Code].....

View 6 Replies


ADVERTISEMENT

C++ :: Class Instances To Text File

Mar 29, 2015

Code:
#include<iostream>
#include<conio.h>
#include<string.h>
#include<ostream>
#include<fstream>
#include<iomanip>
using namespace std;
class MathProblem {

[Code] ...

So my program is quite simple, have the user answer the answer to a question, and then compare with the correct answer. I needed to implement an inheritance of MathProblem in my second class aswell.

The program runs as I intend but I wish to have the data forwarded to a text file. After that I must read back to the command prompt the text file contents. It's fairly easy for simple statements but I don't understand how to forward all my data from my classes.

View 3 Replies View Related

C++ :: Static Const Class Instances?

Jun 17, 2012

i have this rather large class, which (in a way) somehow resembles a custom dialog control). This control is supposed to display data, which it does just fine. To do so, it maintains a

byte settings[10];

array, which holds information on how to display the data.

There are multiple ways to represent this custom set of data.In order to remain flexible in representing it, i thought of implementing some sort of DisplayProvider, which can be registered to the base class and provides that settings byte array.

Preferably, i would now have a set of static const instances of this provider.Using a struct would work nicely here:

PHP Code:

struct DisplayProvider
{
int settings[10];
}
static const DisplayProvider prov1 = {1,2,3,4,5,6,7,8,9,0}; 

The problem: The DisplayProvider would have to do some pre-processing, before handing over control to the base class, which then does the main work.I would end up with something like this:

PHP Code:

class DispalyProvider
{
baseclass* owner;
 int settings[10];
void PreProcessing(...);//ends up calling the owner.Processing(...) function
}; 

The main thing here is, that i dont really see a way to create a stock of default "static const DisplayProvder = {...}"s, as i could when using a struct.

View 7 Replies View Related

C++ :: Hold Vector Of Pointers In Same Class As Instances Of Those Objects?

Feb 10, 2015

Using SFML, I had a Board class which held multiple vectors of all of my object types in the game, and then it also held a vector of pointers to the memory addresses of these object instances, like this

class Board{
//...
std::vector<AbstractObject*> GetAllLevelObjects(){ return allLevelObjects; }
//so these are used to hold my object instances for each level

[Code]....

When looping through this vector and drawing the sprites of the objects, I get the runtime error 0xC0000005: Access violation reading location 0x00277000. I solved this error by storing the vector of pointers in the class that holds my Board instance, but I'm wondering why only this solution worked? Why couldn't I just have my vector of pointers in the same class that the instances of those objects were in?

View 2 Replies View Related

C/C++ :: Create Class Instances From Text File Stream

Nov 10, 2014

I am trying to do some exercises but am struggling at the moment. The first task was to create a class (Planet), then allow the user to edit their entry or view it.

The second one is to create class instances from a text file. The file contains a new planet on each line in the form: 'id x y z' where x/y/z are its coordinates. As the file can have more then one lines, it has to dynamically create an undefined amount of class instances.

To do this I used 'new' and it works ok - it prints each one out to the screen as you go so you can see it working. However... I'm trying to get into good habits here and am encapsulating the class which is where I am getting stuck. I can read from the class but cannot put the values from the file into the class.. ..using the member functions I have created anyway.

My code so far is:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Planet {
private:
int id=0;
float x_coord=0.0, y_coord=0.0, z_coord=0.0;
public:
int GetID(){return id;}

[code]....

If I change the SetID etc to just p->id, p->x_coord etc it works fine. But I'd rather find a way to do it that keeps the encapsulation. Using p->z_coord etc requires that you change the class variables from private to public.

The question I have been given is this:

Define and implement a function, generate planet, that takes a stream argument that has already been connected to a file (i.e. the argument is istream& fin). The function must create a new instance of planet using new and read its details from the next line in the file.Each line of the file is in the format id x y z.The function must return the newly created planet.

Also, how would you go about 'viewing' one specific class instance once they've been created? So say the file had 5 lines, line three was '4 6 2 6'. How would I go about viewing that planet afterwards? I don't think thats required but... I'm just wondering Although I'm also wondering, are we actually creating a new class instance for each line here? Or just destroying the previous one?

View 14 Replies View Related

C++ :: Read In Lines From A File / Store In Variables Then Construct Instances Of Class

Aug 22, 2013

I can't get my code to compile, i need to read in lines from a file and store them in variables. Then i have to construct instances of my class for how many lines there are in the file and take those variables into them.

I'm getting this error :

"a2.cpp:40: error: cannot convert `Employee' to `Employee*' in assignment"

#include<iostream>
#include<string>
#include<fstream>
void displayInfo();
using namespace std;
class Employee{

[Code] .....

View 1 Replies View Related

C++ :: How To Initialize Static Member Of Class With Template And Type Of Nested Class

Oct 7, 2014

How to initialize a static member of a class with template, which type is related to a nested class?

This code works (without nested class):

#include<iostream>
using namespace std;
struct B{
B(){cout<<"here"<<endl;}
};
template<typename Z>

[Code] ,....

View 1 Replies View Related

C/C++ :: Unable To Initialize Arrays In Class

Jan 31, 2014

I have a class which I need to initialize some arrays upon its creation. At first, I tried doing it like I would in Java -

float xyzw[4] = {0, 0, 0, 0}

but that didn't work. Then I had someone suggest using initialization list. I have done so below-

#include <vector>
#include "Buffer.hpp"
class Vertex {
public:
Vertex() :
xyzw{ 0, 0, 0, 0 },
rgba{ 0, 0, 0, 0 },

[Code]....

However, the above code gives me the following error:

Error1error C2536: 'Vertex::Vertex::xyzw' : cannot specify explicit initializer for arrays

I am using Visual Studio 2013.

Also, is there any way to edit previous posts? I keep making mistakes with the code tags.

View 5 Replies View Related

C++ :: How To Initialize Vector In A Class Object

Mar 6, 2013

I want to make a class, named generation, having a vector<chromosome> type data member.

chromosome is also class name.

chromosome has a 'route' as data member, which type is class TArrayI defined in ROOT package.

the size of route is to be fixed according to parameters of generation class object.

class chromosome{
public: chromosome(){;}
....
protected:
TArrayI route;
};
class generation{
public: generation(int PopSize=300, int numCity = 36){
.........
}
vector<chromosome> Population;
};

I want each element, chromosome of Population, to have a numCity size of route.

View 2 Replies View Related

C++ :: Initialize A Class In A Manner Similar To C Arrays

Jan 6, 2015

In my case, it involves making a wrapper class of sorts for the std::set. I'm wanting to go all-out on it and make some "fashionable" constructors for it, one of which being similar to C-style array initializations.

// C-array initialization.
int array[5] = { 1, 2, 3, 4, 5 };

// Some example usage of what I'm wanting.
Set<long> num_set = { 10, 20, 30, 40, 50 };
Set<std::string> str_set = { "Hello", "I", "am", "a", "set." };

I almost never overload operators when I work--if it can be done with a function, it's done with a function--but I realize that doesn't make the best user-experience when other people come across your code, so that's what I'm trying to improve.

It looks like I'm going to be needing to overload the = operator, no big deal. But the array segment is confusing, since {} is not an overloadable operator in C++.

View 2 Replies View Related

C++ :: Can't Initialize Static Data Member In The Class Definition

Apr 17, 2013

"You cannot initialize the static data member in the class definition — that’s simply a blueprint for an object and initializing values for members are not allowed. You don’t want to initialize it in a constructor, because you want to increment it every time the constructor is called so the count of the number of objects created is accumulated."

Why don't you want to initialize it in a constructor?

Edit: Because every time it is called it will set it back to 0 or whatever the initializing value.

View 2 Replies View Related

C++ :: Read And Write Multiple Class Objects From File - Fstream Won't Work Correctly

Apr 28, 2014

So I have a small program which is supposed to write and read multiple objects from a file, but for some reason it doesn't write the information when I use "fstream" to create the object from the fstream class, but it does when I use "ofstream". Also, it doesn't read the information from the file no matter if I use "fstream" or "ifstream". I watched a video where this exact code worked just fine, but it just won't work when I run it. I'm using Dev C++ 4.9.9.2, I don't know if that has anything to do with it, I also tried it with Code::Blocks, didn't work either.

Here's the code.

#include <iostream>
#include <fstream>
using namespace std;
class Person

[Code].....

View 3 Replies View Related

C++ ::  Calling All Instances Of Object?

May 28, 2013

So I am wondering how I would go about calling a function for all instances of an object. I tried googling it, but all I saw was solutions like making an array of pointers to the objects. What if I don't know how many objects there will be? Isn't there an easier way?

View 19 Replies View Related

C++ :: Set Member To Same Value In All Instances Of Templated Structure

Sep 3, 2013

template <typename T> struct avl_tree {
T data;
int balance;
struct avl_tree <T> *Link[2];
static int (*comp)(T, T);
};

In main, I have a function like so:
int compare(int a, int b) {
return ( a - b );
}

Now how do I assign the function pointer in my avl_tree class to the compare function?

I did this:
int (avl_tree<int>::*comp)(int, int) = compare;

But I got the compiler error:
Tree_Test.cc: In function ‘int main()’:
Tree_Test.cc:27:42: error: cannot convert ‘int (*)(int, int)’ to
‘int (avl_tree<int>::*)(int, int)’ in initialization

View 12 Replies View Related

C++ :: Search Specified File For All Instances Of Substring

Mar 24, 2012

I'm trying to search a specified file for all instances of substring "abbaa."

The professor is making us use a 6x3 array in order to understand finite state machines.

Well the code I wrote runs perfectly, but the case for '/n' doesn't catch. It just flows through without it.

Significant portion of code:

Code:
if(fin) {
fin >> inChar;
while(fin) {
switch(inChar) {
case 'a':
currentState = state[currentState][a];

[Code] .....

View 3 Replies View Related

C :: Making Fork Call And Have The Instances Run Every Five Minutes

Dec 18, 2014

Understanding Fork() calls. I have to write a C program in UNIX machine, and make two Fork Calls Inside it and have these two instances run every five minutes all round the clock. How to achieve this.

View 1 Replies View Related

C/C++ :: Create Local Instances Of A Global Variable?

Oct 4, 2012

is it possible to have a global variable pointing to a different address depending on the thread?

Imagine one would like to use threads with the loop:

for (i=0;i<n;i++){
globalPointerVariable=getAddress(i);
DoThingsUsingThe_globalPointerVariable();
}

View 4 Replies View Related

C :: Filling Structure Client / Storing Different Instances In Array

Mar 31, 2013

Here is what I have going on.

Code:

struct client {
char firstName[stnd];
char lastName[stnd];
long ID;
char email[stnd];
float funds;
float wager;
}

typedef client...I would like to have these fields filled with this function below and stored in an array... Basically Multiple users and this is my function for it, if I can get it to work proper -.- .... I don't get syntax errors but I do get warnings

Code:

void getct(client *cl, int *pclientCounter) {
char input[buff];
char *pinput = NULL;
int typef = 0;
int lengthf = 0;
}

[code]....

View 3 Replies View Related

C/C++ :: Remove All Instances Of Element Within List - While Loop Error

Jun 23, 2014

I am getting an error with my while loop(feels dumb) when running this code that I am allowed to modify. It is to remove all instances of an element within the list.

The loop is whithin this function:

void arrayListType<elemType>::removeAll(int location)

I have attached both the header file and main function file in .txt format.

void arrayListType<elemType>::removeAll(int location)*

Attached File(s) : 
header.txt (12.23K)
main function.txt (2.95K)

View 2 Replies View Related

C :: Compiling Sudoku Program - Declare Constant Instances As Global Variables

Sep 18, 2013

I am trying to compile a c program for sudoku. I have declare const instances as global variables, but when i try to compile the code it says that my declarations are not constant, here is some of the code.

#include <stdio.h>
#include <assert.h>

const int GRIDSIZE = 3;
const int GRID_SQUARED = GRIDSIZE * GRIDSIZE; //this line
const int ALL_VALUES = (1<<GRID_SQUARED)-1; //and this give//the error
int board [GRID_SQUARED][GRID_SQUARED];

View 3 Replies View Related

C++ :: Dynamic Memory - Create Multiple Instances Without Explicitly Call Delete

Mar 28, 2014

look at this code:

#include <iostream>
using namespace std;
class teste

[Code]....

Each time i call "x = new teste();" the previous object is deleted? Does this code cause any sort of memory leak?

View 1 Replies View Related

C :: How To Typecast Correctly

Feb 17, 2015

so i have this problem with my code ( not running)i want to read ( 2 double numbers x,y) and ( one integer z) then calculate reminder of x and y ( after they both converted to integer) and the formula : x^2 + y^2 + z^2and : x^z + y^z

here is what i came up with :

Code:
// compute.c

#include<stdio.h>
#include<math.h>
int main(void)
{

[Code]....

it also says in q : be sure to test the user input to make sure x,y,z are positive . any negative or zero should not be accepted and must print error msg ==> do i have to have an if statement here ? or the while loop is enough ?

View 9 Replies View Related

C :: How To Use Pow Function Correctly

Jan 23, 2015

I'm working on a school assignment that asks us to make code calculating the quadratic formula.

Code:

#include <stdio.h>
#include <math.h>
int main(void) {
double a = 0;
double b = 0;
double c = 0;
double discriminant = 0;
double solution = 0;
double solution2= 0;
}

[code]....

View 4 Replies View Related

C++ :: Board Not Printing Correctly

Jul 19, 2013

I'm writing a version of the classic Snake game. However, my board is not printing correctly. The right hand border is in the incorrect location. Also, when I randomly generate where the food ('X') is located, it only generates on the edges of the boundaries.

#include <iostream>
#include <cstdlib>
using namespace std;
const int ROWS = 21;
constint COLS = 61;

[code].....

View 5 Replies View Related

C++ :: GPA - Program Not Averaging Correctly?

Feb 7, 2015

My program isnt averaging correctly.

#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
using namespace std;

struct nameGPA {

[Code] .....

View 4 Replies View Related

C++ :: CPP File Not Opening Correctly?

Nov 2, 2014

When I try to open the cpp source in Visual Studio, it just opens a blank notepad window. The cpp file says its 4 kb and there was code in it.

View 5 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved