C++ :: How To Avoid Redundant Code In Classes

Sep 4, 2014

ISSUE: How to avoid redundant code in c++ ?

Problem:Say I have a Base class called Car and it has 3 derived classes say Ford, Honda and Audi.

now the issue is all 3 derived classes have exactly same code but minor difference in calling member functions of their r respective engines( these engines have separate class) . example ford class calls code which is exactly same as other 2 classes but do call something like ford_engine-> start() ford_engine->clean() bla bla bla .

//ly honda calls honda_engine->start() honda_engine->clean();

//ly Audi calls audi_engine->start() audi->clean();

now here the issue is it has redundant code in all 3 places with minute difference. Hoow I can have code at one place most probably in Base class and all derive classes uses same code.

View 1 Replies


ADVERTISEMENT

C :: Method Or Process For Reducing Redundant Code In Nested Loops

Nov 8, 2014

Have an assignment due in a few weeks and I'm 99% happy with it My question is is there a method or process for reducing redundant code in nested loops. Ie my code compiles and runs as expected for a period of time and after a few goes it omits a part or prints an unexpected out ext so basically how to find when the redundancy occurs with out posting my code so I can learn for my self?

View 3 Replies View Related

C++ :: Untraceable Error In Code Involving Classes

May 12, 2013

I've written a c++ program that contains the following classes: class Shape, Circle, Ellipse, Rectangle, Triangle. All the classes are a subclass of class Shape. They syntax of their definition is fine, I see no visible errors. This is the code:

#include "graphics.h"
//#include <iostream>
using namespace std;
const float Pi = 3.141;

float distance (int x1, int y1, int x2, int y2) {

[Code] ....

Now when I declare a variable of each subclass in the main, I get an error on two of the classes.

int main () {
Circle a;
Rectangle b;
Ellipse d;
Triangle c;
int x1, y1;
float length;

[Code] .....

...And there's a bunch of similar if conditions. My compiler gives an error under b and d, i.e. the Rectangle object and the Ellipse object. The error is, "Expected a ';'" . I have quadruple checked every inch of my code and as far as I can tell, there are no missing semicolons. Where this ";" belongs ....

View 2 Replies View Related

C++ :: Changing Variables In Other Classes Code Blocks?

May 20, 2013

I want to make a basic RPG text based games with multiple classes. but I wan to know how In one class I make a variable and in another and can call the variable.

for exmaple

class2:
int hi = 1;
class1:
class2 a;
hi = 2;
cout << hi;
2

View 1 Replies View Related

C :: How To Avoid Negative Output

Jul 12, 2013

I have a c program that I partially have working. The problem is basically writing a program that allows the user to input the amount of calories they plan to eat a meal and disperse the calories from top to bottom. My program produces the output in the example if I enter 1050 but the issue I noticed if the number of calories is just enough to cover the burgers I get negatives in the other variables.

For example, if I enter a total amount of calories of 1050, I can eat: Output: 2 burgers @ 770 calories (1050 - 770 = 280 calories remain) 1 bag of pretzles @ 170 calories (280 - 170 = 110 calories remain) 1 pear @ 80 calories (110 - 80 = 30 calories remain) 6 tsp. ketchup @ 30 calories If I input 1050 I get the above output but if I input a different integer such as 2000 this is my output 5 burgers @ 1925 calories 0 bag of pretzles @ 0 calories -1 apple @ -80 calories -35 tsp. ketchup @ -175 calories I can't give the full code since this assignment holds a lot of points and was up all night getting it work.

So I'll provide pseudocode

define all 4 variables burger 385, pretzel 170, pear 80, ketchup 5 print out text How many calories can you eat prompt user input
Divide user input into burger How many burgers can bet eaten subtract calories eaten from original user input
Divide calories left into pretzel How many bags can bet eaten subtract burger calories from pretzel calories
Divide calories left after preztel into pear How many pretzels can be eatn subtract pretzels calories from pear calories
Divide calories left over into ketchup how much ketchup can i use show on screen (int total)of burgers @ (int calorie total) calories show on screen (int total)bags of pretzels @ (int calorie total) calories show on screen (int total)pears @ (int calorie total) calories show on screen (int total)teaspoons of ketchup @ (int calorie total) calories

The problem I see is that subtracting the calories from the pear from the left over calories of the pretzel calories leads to a negative. If leftover calories minus 80(pear int) its less then 0 . The calculations from the pear onward to ketchup become incorrect resulting in negative output.

View 6 Replies View Related

C/C++ :: Avoid Using The Goto Function?

Dec 17, 2014

I've been making an RPG in C++ and I've used goto all throughout the program. After receiving an error and Googling how to fix it, I read that you shouldn't use goto. What can I use as a instead of goto, which isn't 'considered bad programming practice'?

View 9 Replies View Related

C++ :: Way / Pattern To Avoid Copying Data

Apr 19, 2013

I have a class buffer, which holds a std::string as member, and a socket_receive function:

struct buffer {
string data;
buffer() {}
buffer(buffer& b) : data(b.data) {}
};
buffer socket_receive() {
buffer tmp;
tmp.data = "1234";
return tmp;
}

so when I write

buffer b = socket_receive();

there is a copy constructor, and the tmp variable is constructed and destructed, is there anyway to improve the performance?

I tried the new c++11 move(), but seems even worse, I must be doing wrong with move(), but I don't know how.

#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct buffer {
string data;

[Code] .....

View 4 Replies View Related

C# :: How To Avoid Duplicate Updates In SQL Query

Jun 13, 2014

I have table called leavetable where in i have the fields eid, lfrom,lto, reason,status an employee will insert these fields in the leave form except status, status will be updated by admin but there is no unique field in the table so when the admin updates the status as cancel for an id emp001 so whereever this id is present in the table its getting updated to cancel even though it is approved previously.. How to avoid this duplication ?

SqlConnection con = new SqlConnection(Connectionstring);
con.Open();
string sql = "update leavetable set status = '"+status+"' where eid = '"+textBox1.Text+"' and noofdays = '"+textBox5.Text+"'";

[Code] .....

View 7 Replies View Related

C/C++ :: How To Avoid Replacing Element In Array

Oct 6, 2014

I am working on a parking lot scenario project using multidimensional arrays. The parking lot has 8 rows and 10 parking spaces in each row. Altogether there are suppose to be 30 cars parking in the lot and arrive in numerical order. I am suppose to generate a random number to represent the row and another to represent the space in the row.

The problem I have is that a few of the elements are being replaced. The project requires the car to check if the space is taken, if so it is to find another one. Here is what I have...

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROW 8
#define COL 10
#define CARS 30
void parkTheCars(int result[ROW][COL]);
void displayArray (int result[ROW][COL]);

[Code] .....

View 1 Replies View Related

C++ :: Can Avoid Class Using Array Operator?

Feb 7, 2014

Imagine these simple class:

Code:
class test {
public:
void write(string a) {
cout << a;
}
};

(these class wasn't tested... it's for these question)... Can avoid the class use the array operator('[]')?

View 7 Replies View Related

Visual C++ :: How To Avoid Memory Fragments

Mar 4, 2015

I am developing a Visual C++ application. There is an object called CMyObject, as follows:

typedef CMap<UINT, UINT, void *, void*> CMyMap;
class CMyObject {
public:
CMyMap *m_pMyMap;
"Some other member variables"
}

Some instances of CMyObject contains a map, some not. Therefore, to save memory, I define a pointer m_pMyMap and create a new CMap object only if the instance contains a map.

When I test my app, with the increase of the CMyObject instance, the number of memory blocks allocated and deallocated is also increasing. There are a lot of fragments during this period. To prevent this, I try to override the new/delete operator for CMyObject and CMyMap. But still find many fragments. So I try to trace into the MFC source codes for CMap. I find CMap is just using an internal buffer to store the hash table(m_pHashTable), as follows:

m_pHashTable = new CAssoc* [nHashSize];

And for each hash entry, it uses:

P = (CPlex *)new BYTE[sizeof(CPlex) + nMax *cbElement];

To allocate the spaces.

I believe these two may be the reason of the memory fragments and want to eliminate them. However, is there a way to override the new/delete operator for codes such as:

new CAssoc* [nHashSize]
and
(CPlex *)new BYTE[sizeof(CPlex) + nMax *cbElement]

So that the spaces will be allocated from my own memory manager instead of from the default heap?

View 1 Replies View Related

C++ :: How To Avoid Using Backspace Character With Push Back

Mar 28, 2014

How to avoid using Backspace character with push_back? I'm making a software as an ATM, so when the user try to enter the password the user only sees *******, but when trying to delete it doesn't delete a character. It just adds a new one. Here's my code:

string password2 = "";
cout << "PASSWORD: ";
ch = _getch();
while(ch != 13) //character 13 is enter {
password2.push_back(ch);
cout << '*';
ch = _getch();
}

And also, I try to use pop_back(); but it doesn't work either.

View 6 Replies View Related

C++ :: How To Avoid If Fstream Opens A Directory (infinite Loop)

Jun 10, 2013

If the filename below is a directory, then the following loop goes to infinite.

std::ifstream in;
in.open(filename, std::ifstream::in);
if(in.fail()) return;

[Code].....

View 1 Replies View Related

C++ :: Array Of Classes With Classes Inside

Oct 5, 2013

I have an array of (Student)classes created in Manager.h, which contains a new instance of class Name (name),(in Student.h)How would I go about accessing the SetFirstName method in Name.cpp if I was in a class Manager.cpp? I have tried using Students[i].name.SetFirstName("name");

// In Manager.h
#include"Student.h"
class Manager
{

[Code]....

View 2 Replies View Related

C :: Print Out - Array Code And Pseudo Code?

Apr 15, 2013

I have assignment which requires me to print out and array code and a pseudo code. I dont no what a pseudo code is,.

View 2 Replies View Related

C++ :: Reducing Code Duplication From Common Code Calling Common Class

Apr 13, 2014

I have a class 'A' which is almost perfect for my needs. Class 'B' uses class 'A' I've now designed Class 'C' and Class 'D' and noticed that there is a good chunk of code in class 'B', 'C' and 'D' for using Class 'A' is duplicated. I've separated out this code in specific, standalone functions in each of the classes. Now I'm wondering where this code should go. At the moment, the functions are duplicated in the three calling classes (B, C and D). Placing the functions into class 'A' would break the single responsibility principle. Inheritance to add functionality would likely break both SRP and LSP. The one that seems that it may work is composition.

However, Is designing a complete class just for a few functions over kill?

Would it be valid for classes 'B', 'C' and 'D' to access both the new class 'E' (which would depend on A) and the old class 'A' (which would have to be the same instance as the instance in the new class 'E'), or should the new class 'E' provide sufficient functionality so that Classes B, C and D don't need to access Class A directly? It would seem that its then an incomplete interface of the original object with additional functionality (ie, incompatible) Or should I do it a completely different way?

View 4 Replies View Related

C++ :: How Do Two Classes Interact With Each Other

Aug 26, 2013

I want to know that how objects of two different classes interact with each other???

View 1 Replies View Related

C++ :: How To Know If Classes In Program Are Being Used

Aug 13, 2014

In this program the intention is to create a menu driven program for a pizza restaurant. I have to use a class called Pizza and have to include at least three public functions; one is called SetSize, another one is called Display, and the last one is called ComputePrice. A small pizza is worth $10, a medium is $14, and a large is $17. Each topping is worth 2 dollars. I know that the program runs correctly, but I have doubts over the classes and function actually being utilized correctly or at all.

Program:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
class Pizza {
private:

int size;
int style;

[Code] .....

View 8 Replies View Related

C++ :: Using Multiset With Classes?

Oct 23, 2013

I'm trying to use multiset with a user defined class "edge". I'm trying to use the multiset as a priority queue, and I've created a "less<edge>" via operator<() overloading.

For some reason, I cannot insert edges into the multiset.

I understand that I might also have to create an "allocator". I got some ideas for creating it at [URL], but still don't know how to define size_type and difference_type.

Attached is my skeleton code, running on Windows 7 (32-bit), under Netbeans IDE, using Cygwin g++ 4.7.3.

How can I get this to work? What is important is that I get a priority queue working with my edges, prioritized by the weight.

#include <iostream>
#include <set> // for multiset
using namespace std; // assume std libraries (i.e. std::XXX)
class edge { // node, weight pair
public:

[Code].....

View 3 Replies View Related

C++ :: Derived Classes From DLL

May 5, 2013

I've created a base DLL for all my future DLL's, a way of getting version numbers and such and that compiles fine, but I can't add it into a class for a new DLL. All the headers do have an appropriate cpp to define the function declarations (and they compile fine).

All for the base DLL I have:

LibVer.h
Version.cpp
Function.cpp

LibVer.h

#pragma once
#include <vector>
#define DLLEXPORT 1
#define DLLIMPORT 2
#define DLL DLLIMPORT

[Code] .....

View 6 Replies View Related

C# :: Can Use Variables From Other Classes

Feb 23, 2014

im creating an address book. One address book contains a ListBox, New User button, Edit User and Remove User button. The first form is suppose to allow you to view the users you've created on the ListBox and you can decide whether you want to remove it, create a new one or simply edit the user. Now The second form simply contains labels and textbox along with a save button. I'm having a bit of issue figuring out the ListBox. I want to be able to create a user and have the user be posted on the ListBox. I read that i must instantiate listbox then simply add it. Now on my form2 i have a for loop that loops through an Array of String were all the users will be created on. How can i call that array of string on to the form1?

Form 1:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

[code].....

EDIT:I just figured out that to call a variable from one form to another you simply instantiate the form then simply call it. PS. must be set to public:

ListBox1 createUser = new ListBox1();
createUser.userString[0];

why doesnt it show the windows when i run without debugging?

View 1 Replies View Related

C/C++ :: Get Volume Of A Box Using Classes

Feb 22, 2015

n the requirements it says this;

-create a get and set for height, width, length.
-A default parameterized constructor = 1
-A method to resize the box
-A method to get the volume of the box
-A method to convert the object to a string

My Questions:

The 3 parts I am confused by are the default parameter constructor, the re-size the box and the method to convert to string. For the default parameter part I figured making length, width and height = to 1 would work, but I'm pretty sure thats not what I'm supposed to do.

This is the main file

#include "box_class.h"
#include <iostream>
using namespace std;
int main() {
double length;
double width;
double height;
double volume;

[Code] ......

View 1 Replies View Related

C++ :: When To Use Static Classes

May 2, 2013

I am just wondering what the best practice is for when to use static classes (by static class, I mean a class which has only static attributes and functions).

If you are creating more than one independent object of a particular class, then obviously this should not be static because each object will be the same. But what about the case when you know that you will only ever need one instance of a class? On its own, does this mean that you should create it as a static class?

Personally, I use static class when I want its member attributes and functions to be available globally, which I think is fine. However, I am not sure about the case when I know that only one object will be created - should this be a static class or not?

View 1 Replies View Related

C++ :: Use Of Template Classes In Other Template Classes

Jan 24, 2012

I'm trying to make a template class which holds a template list I made. The list consists of template nodes (another template class I made).

My problem is that in some places (not everywhere) the compiler says that I'm trying to access private members of the node's class.

For example, if I define my node like this:
template<class T>
class CoefNode {
private:
T coef;

[Code]....

View 5 Replies View Related

C++ :: Nested Classes And Structs

Mar 12, 2014

I'm working on a project involving nested classes and structs like this:

Code: class A {
public:class B {
public:f()
{A::C* iCanDoThis; //no errors.
iCanAlsoDoThis->root->.... //this also works fine.}private:A::C* iCannotDoThis //this is what I would like to do.
Has errors
A* iCanAlsoDoThis;};private:struct C
{..data..};

C* root;};

Is it possible make a pointer to struct C a private member of class B?

View 1 Replies View Related

C++ :: Including Outside Functions Into Classes?

Mar 6, 2015

I have a hpp file with a list of inline finctions like this:

Code:
inline int check() {
return 1;
}
inline int check_1() {
return 1;
}

... What I would like to do is to include them into several unrelated classes. How can I do this. Can I just add the hpp inline functions in headers of my class containing files or not. I mean if they are not defined as class functions how can they be called. I don't understan the logic.

View 2 Replies View Related







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