C++ :: Polymorphism On Class Instance Is Not Directly Applicable To Array
Mar 19, 2013
Below code produces run-time segmentation fault (core dumped) when execution reached line 53: delete [] array
Code 1:
#include <cstdlib>
#include <iostream>
using namespace std;
#define QUANTITY 5
class Parent {
protected:
int ID;
[Code] ....
Output of code 1:
Constructor of A: Instance created with ID=1804289383
Constructor of A: Instance created with ID=846930886
Constructor of A: Instance created with ID=1681692777
Constructor of A: Instance created with ID=1714636915
Constructor of A: Instance created with ID=1957747793
A::showID() -- ID is 1804289383
A::showID() -- ID is 846930886
A::showID() -- ID is 1681692777
A::showID() -- ID is 1714636915
A::showID() -- ID is 1957747793
Try to delete [] array..
Segmentation fault (core dumped)
Question: Why does segmentation fault happen in code 1 above?
View 9 Replies
ADVERTISEMENT
Sep 16, 2014
I have couple of objects which are using some amount of methods. Right now my application is not OOP and i am going to transfer it to OOP. So i would create each class for my each object. Almost all methods are in use for each object, the only one thing which is changing some of those objects passing not all parameters inside specific method. I can go two ways one is prepare interface for all methods i got and each of my classes could implement its own definition for it but other way almost all would implement exactly the same methods but with different parameters so maybe its better to create base class then for each object do inheritance from base class (polymorphism). inside base class i can prepare base methods and classes which will inherit from that class would override those methods for requirements they want.
So imagine: You got:
Memory
CPU
Latency
and all of them using mostly all of those same methods (only arguments for one of them could be use different way):
ExecuteQuery()
ExportToExcel()
PopulateDataTable()
PutValueToReport()
Now its better to do like this e.g:
Base class: Stuff
prop: name, id, date ...
methods to ovveride: ExecuteQuery(), ExportToExcel() ...
classes: CPU, Memory, Latency (inheriting from Stuff)
ovveride methods and align its definition for specific class use (remember mostly only passing args are used or not by specific class)
or go with inheritance
Interface SomeMethods
ExecuteQuery()
ExportToExcel()
PopulateDataTable()
PutValueToReport()
and each class would implemet its own definition.
The most important thing is that those every objects mostly using all of those methods and what is diffrence that one object can use all of available parameters inside this method and other one no. What i should do? Go with interface or inheritance and polymporfizm inside base class?
View 2 Replies
View Related
Dec 10, 2014
Having issues with program to create a shape area calculator with circle square and rectangle. the uml goes as follows:
Where the UML has shape as the abstract class with public area():double, getName():string,and getDimensions:string, rectangle derived from shape with protected height, and width, and a public rectangle(h:double, w:double), followed by a derived square from rectangle with just a public square(h:double), and finally a circle derived from shape with a private radius, and a public circle(r:double).
[URL]
Have linked my program and it is giving me the following compiler errors:
error: 'qdebug' was not declared in this scope line 15 of main
error: cannot declare variable 'shp' to be of abstract type 'shape' line 22 of main
error: expected primary-expression before ')' token lines 29 -31 of main
(note previously had qstring as a header file yet changed to string since I was getting error qstring was not declared in this scope.)
View 5 Replies
View Related
Mar 2, 2014
I've been working on this project which inserts data for different types of books lately, and I'm trying to utilize inheritance and polymorphism. The issue I've been having is after I create an object with my MediaFactory, I go to insert data into that type of object, but it won't reach the correct child class. The parent class in this case is MediaData. The class I'm trying to reach is Childrens, and the class that falls in between is called Book. The function I'm calling to insert the information is setData(ifstream&). This function simply places the information from a txt file into an object with the insertion operator.
Right now the program runs into the setData function of Book instead of Childrens. I need Childrens so I can enter all the required attributes (title,author,year). The call to this function is in MediaManager through the function called buildMedia, and my test is running into the case if (type == 'Y'). From there a pointer of type MediaData is created and pointed to a new object returned of type Childrens. I'm using my debugger in Xcode which does show that the correct object type (Childrens) was created.
I've tried a couple things so far. First I created another function called getData. From there I passed in *media and infile (txt input file) into that function, which then passed it right into setData with a pointer to the object and infile in the parameter. That didn't work, so I also tried going back into Childrens and removing MediaData from all my virtual functions and replacing it with Book. I got the same result when that happened; It morphed into Book class instead.
I have a portion of my UML as a reference. Childrens is a Book; Book is a MediaData. I also included all code for MediaManager, MediaHash, MediaFactory, MediaData, Book, and Childrens.
I did not include the operator overloads in the .cpp files to eliminate some redundancy.
//-----------------------------------------------------------------------------
// MediaManager.h
// Manager class for MediaData type objects
//-----------------------------------------------------------------------------
#ifndef MediaManager_H
#define MediaManager_H
#include "MediaHash.h"
#include "MediaFactory.h"
#include "MediaData.h"
using namespace std;
class MediaManager {
[Code] ....
View 3 Replies
View Related
Oct 19, 2014
I am making a very basic parent/child class based program that shows polymorphism. It does not compile due to a few syntax errors reading "function call missing argument list. Lines 76 and 77, 81 and 82, and 86 and 87.
#include<iostream>
using namespace std;
class people {
public:
virtual void height(double h) = 0;
virtual void weight(double w) = 0;
[Code] ....
View 4 Replies
View Related
Jan 26, 2015
I'm trying to use a class member to initialize the dimension of a matrix. I have two issues. Here is the code (.h) simplified :
#include <vector>
#include <array>
#include <typeinfo>
template<typename T, std::size_t N>
struct md_vector {
[Code] ...
error: invalid use of non-static data member ‘OptimalSamplingStrategy::_nbMorph’|
I can't use a class member directly in the header file (here _nbMorph).
It was an issue I got before and that I didn't solve as I succeed in finding other ways. I don't think it's possible here.
View 1 Replies
View Related
Mar 1, 2013
I am facing a real-life problem, it can be simplified as below:
#include <iostream>
using namespace std;
class B;
class A {
public:
void f1(A a) {}
void f2(B b) {}
[Code]...
There is no problem at all with the f1(), it compiles and executes without any problem. But f2() gives compilation error. How to solve this?
The error message is: error: 'b' has incomplete type This is just to define the function f2() in a class, that uses an instance of its child class as one of its arguments.
View 11 Replies
View Related
Nov 24, 2014
I'm learning OpenGL using the C API and some of the functions' argument types have proven a bit challenging to me.
One example is the function Code: glShaderSource(GLuint shader, GLsizei count, GLchar const** string, GLint const* length); It resides in foo() which receives a vector "data" from elsewhere Code: void foo(std::vector<std::pair<GLenum, GLchar const*>> const& data); To pass the pair's second element to glShaderSource's third argument, I do the following:
Code:
GLchar const* const source[] = {data[0].second};
glShaderSource(..., ..., source, ...);
Now I have two questions regarding this:
1. Can I initialize a char const** via initialization list, the way I do a char const*?
Code:
// this works
std::vector<std::pair<GLenum, GLchar const*>> const shader_sources = {
{GL_VERTEX_SHADER, "sourcecode"},
{GL_FRAGMENT_SHADER, "sourcecode"}
};
// but is this possible?
std::vector<std::pair<GLenum, GLchar const**>> = { ??? };
2. Is there an alternative to creating a temporary GLchar**, even though that's specifically what the function wants?
View 2 Replies
View Related
Jul 3, 2014
There are two ways to access the members of class A inside class B:
1) Making an instance of class A in class B
2) Deriving class B from class A
So what is the basic difference in both ways as we can do same kind of work with both ways?
View 1 Replies
View Related
Oct 4, 2014
I'm currently learning the Qt framework and doing my first tutorial. Straight away I saw something that baffled me:
notepad.h
Code: namespace Ui {
class Notepad;
}
class Notepad : public QMainWindow
[Code] ....
Note the ui pointer and the heap allocation in the class constructor; I can't wrap my head around why one would do this. What's going on here?
View 5 Replies
View Related
Nov 6, 2014
I am putting a instance o the Vehicle Class inside the constructor of the Calculate Class then calling it later. I get a warning saying the variable is not used and a error when I try to used the functions from the vehicle class saying use of undeclared identifier.
Code:
#include <iostream>
#include "Calculate.h"
#include "Vehicle.h"
#include <fstream>
Calculate::Calculate(){
[Code] ....
View 9 Replies
View Related
Feb 12, 2014
Okay so I have a class Student, which takes a number and a vector as a parameter for the constructor. Everything works well, until I output the values of the vector for every instance. The problem is that the same vector is being shared with EVERY instance I create, but I want it to be unique for every single one!
//Student.h
#ifndef __Grade_calculator__Student__
#define __Grade_calculator__Student__
#include <iostream>
[Code].....
View 1 Replies
View Related
Nov 24, 2012
I was wondering if (in C++) you can instantiate a class (class foo) then have said class return the already instantiated object. (foo::instance())
In other words, can I have a class return it's-self via it's own methods? I want to be able to create a class (i.e. class foo) early in my program so it is already setup and ready to go. Then, farther down the line, I want to be able to call functions from that class without having to pass that object as an argument to my calling function. Can I do something like so:
MyClass::ReturnSelf()->foo();
or
MyClass::ReturnSelf().foo();
View 13 Replies
View Related
Mar 2, 2014
I have a background in c# and am very frustrated with c++. If I created a class in c# like so:
public class Memory{
int x = 0;
int y = 0;
int height = 0;
int width = 0;
string firstname = "Bob";
string lastame = "Chester";
}
and then created a new instance of this class from a separate class by doing:
public class Main{
Memory mem = new Memory();
}
I have raked the internet for a way to create a new instance of a class in c++ while keeping its default values and have come up empty handed.
View 13 Replies
View Related
Jan 17, 2014
I know that it is possible to pass a class instance to a function, but in my experience, if said function changes any variables of the class, they don't actually get changed. For example, we have class object, that has a member int number = 5. Lets say we have two functions, func1() and func2, which are not members of class object. If we pass object to func1() which, lets say, increases number by 5 (so now number = 10), at the end of that function number still = 5.
Is there a way to bypass this and have functions alter class variables permanently?
I know that I can pass variables by reference, but, in my experience, such a thing does not work with vectors (which I am also dealing with), so simple passing the desired variables by reference won't work.
View 5 Replies
View Related
Sep 4, 2013
I'm trying to learn as much C++ as I can. I was writing a program that mixes linked lists and classes. There is the class "Obj" which only holds an integer called 'data' and the classic "struct node" structure for linked list, but this time the "node" structure will hold an instance of "Obj" Class and the next* pointer.
#include <iostream>
using namespace std;
class Obj {
private:
int data;
public:
[code]....
View 2 Replies
View Related
May 22, 2013
So I have a class that is like this:
class card {
public:
int id;
int val;
};
card card1;
card1.id = 1;
card1.val = 2;
card card2;
card2.id = 2;
card2.val = 45;
etc...
So my question is firstly, is there a better way to implement this? (a vector of classes or something maybe?) and how can I call up a specific instance of the class. For example, if I want the val of a specific instance of the class, how best can I do that?
View 3 Replies
View Related
May 6, 2014
I'm trying to change the values of some instance variables in my Controller Class so that when the user inserts values into main class it changes for Controller.
class Controller {
public:
Controller();
~Controller();
double PCFreq;
__int64 CounterStart;
[Code] ....
The user should be able to choose which foo the want to use. So I create an object of controller in main like this
Controller* con = new Controller()
Now my issues is, when I take user input (an integer) and try to do this
con->choice1 = choice1;
only the object of con's choice1 is = to user input.
However back at the class for Controller, choice1 hasn't received a value.
I can't initialize through Controllers constructor because I get the user input through a switch statement and the range of con would only be as far as the case.
View 2 Replies
View Related
Dec 4, 2014
I am creating a program that allows a user to create multiple 'sequences' and multiple 'filters' and then apply a filter to a sequence.
Each sequence and filter is an array of values.
How do I go about allowing the user to create a 'new' sequence and then store the location so I can access it again later? Once they have created a new sequence they can go on to create another sequence and ten maybe a filter and then another sequence etc etc .. and then they can select sequence 1 and edit the values if they so wish.
They would be asked how many sample values for the sequence, and then I would create a sequence with that many values and an id (1,2,3,4...). They could then enter this id to view/edit the sequence.
The entering/editing values part I am fine with. I just don't know how to allow them to create multiple new instances of a class without using an array so something like..
sequenceClassName somearray[10];
int i;
*create a new array*
somearray[i].create_class(how_many_samples)
i++ //so next sequence they create is 2,3,4.. etc
- this then calls the member function that creates an array using 'sample_values = new float[how_many_samples]' and the user can input their data and edit it whenever by entering the id which will correspond to the somearray[i].
However that approach only allows them to enter a maximum of 11 sequences. It all depends on how big I make that initial array and it just seems like the wrong way to do it.
( how to interact with them, just how to create multiple classes and recall them later to access the data!)
View 2 Replies
View Related
Apr 27, 2014
I am new to C++. I am trying to create 5 instance object of class Test. I wonder if these two codes are the same.
Test testArray[5];
//which one is the correct way or what is the correct way?
for(i=0;i<5;i++)
{
Test testArray;
}
View 2 Replies
View Related
Aug 25, 2013
I'm new in object oriented programming. I need creating a global object/instance of a class, that can be used by any function.
View 19 Replies
View Related
Jan 15, 2015
Let's say I reference a dll in my project that has an abstract class in it:
public abstract class Module {
public string type;
public abstract string doSomething();
}
And then I have an Assembly object, loaded from a dll that is not referenced in project, but rather loaded during run-time, containing:
public class Tester : Module
{
public static string type = "Test";
public override void doSomething() {
//Stuff being done
return "hello";
}
}
How can I get the value of "type" in the class that is loaded during runtime? How do I use the "doSomething" method of it and get the returned object?
View 8 Replies
View Related
Jan 13, 2015
Here's the problem I want to intialise different classes based on user input. I've tried using an IF statement but the scope of an if statement would mean the rest main program wouldn't be able to see it.
View 12 Replies
View Related
Oct 20, 2012
I have a class that is a template, I have to declare it in my main but i want the user to choose what type of data they will use in the class, I cant just declare myclass my, i have to use myclass<int> my, how can I change so user can select the proper datatype to use in the class.
View 5 Replies
View Related
May 23, 2013
I need to create an object of a mfc derived CFormView class that's not in the doc/template (a second view class). But it was generated with a protected ctor. Here's the code explanation with comments.
I'm thinking all the normal classes of the Doc/View template are created starting with this code, but within the template code base.
Code:
CSingleDocTemplate* pDocTemplate;
pDocTemplate = new CSingleDocTemplate(IDR_MAINFRAME,
RUNTIME_CLASS(CViewSwitchDoc), //<-expands to-> ((CRuntimeClass*)(&CViewSwitchDoc::classCViewSwitchDoc)),
RUNTIME_CLASS(CMainFrame), // main SDI frame window
RUNTIME_CLASS(CViewSwitchView));
But I have generated "another view" using the "Add Class" Wizard, it's a derived class of mfc CFormView which I named ViewForm. However I'm having a problem creating an instance of it because of the generated protected ctor and pulls a compile error of not being able to access ctor. Below are the header and implementation files of this said ViewForm class. How to create an object of this view ? Did I go about it all the wrong way since it's not in the doc/template group ?
// ViewForm.h file
#pragma once
// ViewForm form view
class ViewForm : public CFormView {
DECLARE_DYNCREATE(ViewForm)
[Code] ....
View 5 Replies
View Related
May 3, 2013
I'll just tell you in short how my Problem looks like: I should implement a New Class in a SourceCode i didnt write myself. The source code is extremely sized (i think approx >100.000 Lines of Code), so i dont want to change too much in it in order to get my Implementation done.
MY problem looks simplicified like that: Starting from 3 classes and my new class the pseudo-code looks like that:
Class1(){
float* m_CalibX, m_CalibY;
.. }
Class2(){
char* m_ImageData[];
[Code] .....
So, i need Parameters from 3 different classes to insert in my NewClass. The 3 Classes dont know anyting about each other. So, i need to implement a Class-Instance from Type NewClass which is known by the other 3 Classes. I did solve it in this way:
//ClassInstance.h
#include "NewClass.h"
static NewClass ClassInstance
I just wrote a headerfile with a class-instance which is getting included by the other 3 Classes. So they all know the same Instance and writing their Parameters into it. Is this a decent solution or could it happen to get bugs/ logical mistakes with it?
View 2 Replies
View Related