Questions tagged [constructor]

24

votes
3

answer
1.3k

Views

Why doesn't the standard consider a template constructor as a copy constructor?

Here's the definition of copy constructor, [class.copy.ctor/1]: A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments...
geza
1

votes
1

answer
46

Views

Perfect forwarding an STL container to a template class

Trying to use perfect forwarding to pass a sequence container to a class that is templated. For instance: template class A { public: using ContType = TContainer; //This works for R-value references only explicit A(ContType&& container) : internalContainer(std::forward(container)) {}; //This does no...
Harvey Ellis
1

votes
2

answer
46

Views

Performing initialization of templated class using other templated classes in variadic arguments of constructor

I wanted to create a simple HTML dom builder in C++ and decided I would use a templated tag class to describe the type of tag this was. I already used other methods to create the DOM in C++ with some success, but the design wouldn't handle raw strings, so the move to a templated class may assist me...
J. Willus
16

votes
4

answer
887

Views

Why can I not instantiate a class whose constructor is private in a friend class?

I have two classes; Salary that is intended to hold information and calculations regarding the salary of an employee and Employee that has an object of type class Salary and some members like name and address of the employee... What I want to do is to prevent class Salary from being instantiated exc...
Syfu_H
0

votes
0

answer
29

Views

How I make an overloaded operator illegal?

I'm planning to implement an unique smart pointer in c++, so I want to make illegal to use the '=' operator. How can I do it? This is the class that I have: template class uniquePointer{ private: dataType *pointer; public: uniquePointer(){ pointer = nullptr; } uniquePointer(dataType *value){ poin...
BelisaDi
7

votes
4

answer
193

Views

Why I cannot instantiate a class whose constructor is private in a friend class?

I have two classes; Salary that is intended to hold information and calculations regarding the salary of an employee and Employee that has an object of type class Salary and some members like name and address of the employee... What I want to do is to prevent class Salary from being instantiated and...
Syfu_H
1

votes
1

answer
12.5k

Views

Assignment operator in linked list C++

I'm trying to implement linked list in c++. I implement my assignment operator like this: // assignment operator template LinkedList& LinkedList::operator = (const LinkedList& rhs) { if (&rhs != this) { Node *tmp = head; while (tmp -> next) { head = head -> next; delete tmp; tmp = head; } tmp = rhs...
齐天大圣
1

votes
1

answer
2.8k

Views

Scala “constructor Stopwatch cannot be accessed in class Main”

Summary on resolution, I thought I was dealing with a Scala problem but it turns out Stopwatch and Scala Logging have private constructors, and I was not calling the proper public methods to instantiate them. gzm0's answer below points this out. Trying to use Guava Stopwatch and Scala Logging, no ma...
JimLohse
1

votes
1

answer
231

Views

Call non-static function in constructor initialization list, C++

I am currently optimizing my code, and I came to a point where I was tempted to use the following pattern when initializing my class: class MyClass { MyClass(int x) : _x(x), _collection(createCollection()) { } int functionThatDependsOnTheStateOfTheClass() const { return _x; } private: std::vector cr...
4-bit
-2

votes
2

answer
109

Views

Code Comparison : Which code is better to use in terms of efficiency?

Which code is better to use : to initialize string ? bool flag = /*function call...*/ string str = 'abc'; if(flag) str = 'bcd'; Or string str; if(flag) str = 'bcd'; else str = 'abc'; Or string str('abc'); if(flag) str = 'bcd'; Thanks in advance.
Amit Kumar
4

votes
3

answer
120

Views

Java bad practice doing: new… ().doSomething()?

I just saw a piece of code that had some classes with only one method. I picked an examples: public class TempDirCleanupProcess { public void cleanup(final File directory) {} } Then, later on in the code the method was called the following way: new TempDirCleanupProcess().cleanup(tempDir); Now I am...
ItFreak
1

votes
1

answer
52

Views

how to determine the constructor which called with empty braced initializer?

I tested the following code on two different compilers, I could not determine how the object w2 is constructed. #include using namespace std; class Widget { public: Widget() { std::cout
Abdulrhman
1

votes
1

answer
129

Views

C++ method in thread. Difference between passing: object, object's address, std::ref of object

I am trying to execute an object's method in a C++ thread. I am able to do it, by passing the method's address and the object (or the object's address, or std::ref(my_obj)) to the thread's constructor. I observed that if I pass the object, rather than the object's address or std::ref(my_obj), then...
Michele Piccolini
1

votes
2

answer
35

Views

Using alternative super class constructor in child class instantiation

I have a base class with two constructors, and a child class which has one constructor. Is it possible to instantiate a child class using the second base class constructor? Example code: abstract class RuleCondition(rule:Rule, field:String, equal:Boolean, inverted:Boolean) { // alternate constructor...
user826955
1

votes
3

answer
31

Views

How to create an array in constructor that will be used later

I am making a Matrix class and want to make the constructor input the Matrix type too. How can I initialize a specific type 2d array? public class Matrix { public int[][] matrix; //?? Matrix(int x,int y,string type) { switch (type) { case 'int': //initialize a int 2d array case 'double': //initializ...
Clement Hui
1

votes
3

answer
59

Views

Getting the object variable name for the new object

I have an object constructor such as: function myObjConstr () { console.log(object_name); } I want this results: var name1 = new myObjConstr(); //print in console log 'name1' var nameff = new myObjConstr(); //print in console log 'nameff'
Mostafa Maher
1

votes
1

answer
123

Views

C# - Allow Inheritance but Forbid Direct Use of Constructor

I want to allow inheritance, but forbid the direct construction of any of the inherited classes. Instead, I want to force the usage of the custom method New(). The goal is to make sure that every instance of inherited classes is a transparent proxy of itself. In this case, it's not possible to make...
Mr.Yeah
1

votes
2

answer
517

Views

Constructor Specialization with Templates

#include using namespace std; template struct MyType { public: T cont; MyType(T value) : cont(value) {} MyType(int value = 1) : cont(value) {} MyType(double value = 1.2) : cont(value) {} }; int main() { MyType a; return 0; } This code gives these errors: error: 'MyType::MyType(int) [with T = int]...
DarkoNaito_09
1

votes
2

answer
61

Views

How to write a constructor for a class who includes another class?

I write a 'Student' class which has two classes called 'Course' and 'Score' as its members. Now I write a constructor for initialization of 'Student' class and get these errors: 1.missing default argument on parameter 'e' 2.no matching constructor for initialization of 'Student' 3.candidate construc...
CaSdm
1

votes
1

answer
35

Views

child extended class method calls its super version but that still only sees child data

class B extends class A. I'll call A the parent and B the child. Both have constructors. B calls super() inside of its constructor. Both have a method with the same name. Perhaps just by coincidence or mistake both have a 'this.x' variable. There then becomes no way to access the parent's this.x...
user244488
1

votes
0

answer
66

Views

Copy constructor called on object instantiation

I may just be miss reading this code but in my attempt to call the default constructor, the code instead calls the copy constructor on my proposed creation. Could someone give me a knowledge bomb on where my mental model and this code done meet :-/ Below is the code written, its a rough outline fo...
Theko Lekena
1

votes
0

answer
48

Views

Initializing an array of structs when no explicit constructor is provided

If I have a struct: struct S { int x = 0, y = 0; }; Then, is it OK to initialize an array of such structs like this? S s[5] = {}; so that x and y in each struct is 0? So, do x and y become a part of the implicit constructor? And if yes, do I need the = {}; then at all?
user3496846
1

votes
1

answer
97

Views

How do define a constant value from user input after class construction

As part of personal Arduino project, I have added an initial 'input' stage that asks the user to enter an integer representing the number of vials in their carousel (that particular info is not relevant to the issue, I just thought I'd better mention it.) This input is received via LCD button keypad...
Anthony the Kid
1

votes
1

answer
59

Views

Explicit conversion with Assignment

A simple class with explicit conversion constructor. class MyDouble { double d; public: MyDouble() : d(0) {} explicit MyDouble(double d_) : d(d_) {} MyDouble & operator =(double d_) { d = d_; return *this; } }; I add an assignment on purpose to make it can be assigned constructed from double. MyDoub...
phy nju
1

votes
0

answer
52

Views

c++ / Visual Studio 2010 / add just-constructed-element to list

I'm on a big C++/stl mystery with Visual Studio 2010 : I push back an object to a list, and when I access to it, I get partially un-initialized data. Here is a very minimalist sample of code that produce this behavior : #include #include #include using namespace std ; struct Foo { Foo ( int x , i...
Captain'Flam
1

votes
1

answer
84

Views

How to use and print from constructor

I'm trying to create a simple card game where two players receive random cards. I have decided to use the constructor to make it simple and use less space. Can someone help me and explain how to generate random card in my main program from my Card class. public class clsCard { private int value; pri...
Bartlomiej Kaczmarek
1

votes
2

answer
39

Views

Issues with validating fields in constructor of a subclass

I am now learning about Java's inheritance. I have total of 3 questions, and thank you for your support. 1st question: Can I validate a class's fields in its constructor? 2nd question: Some people recommended me to throw an exception for validation. Does it mean throwing an exception to the calle...
Tom_the_cat
1

votes
1

answer
106

Views

java: ERROR: “cannot find symbol – class Constructor” when making instance from String, with parameters

I searched through all the questions here that involve 'reflection' to instantiate a parameterised object using a String of the class name, but I cannot get it to work because Java doesn't recognise Constructor as a class. Class myClass = Class.forName('MyClass'); Class[] types = {Double.TYPE, Stri...
John Doe
1

votes
0

answer
384

Views

Matlab error: constructor must preserve the class

connected question: Returning an object of a second class through the constructor of first class but the answer doesn't seem to be of much help for me. I'm having trouble with Matlab constructors. I want to create a class A and a subclass B, such that I can provide the constructor of B with either t...
Kenji
1

votes
1

answer
63

Views

JavaScript Function Constructor Parse Security

When using the Function constructor in JavaScript, a function object is dynamically created from the given code: const input = 'return 2 + 3;'; // (1) const fun = new Function(input); // (2) const ret = fun(); // (3) Assuming the input string (1) is arbitrary user input, is it insecu...
Steven
1

votes
0

answer
32

Views

TypeError: this.initializeSieve is not a function [duplicate]

This question already has an answer here: ES6 arrow functions not working on the prototype? 1 answer Are 'Arrow Functions' and 'Functions' equivalent / exchangeable? 3 answers TypeError: this.initializeSieve is not a function at PrimeGenerator.generatePrimeNumbers. I use constructor mode and proto...
William
1

votes
1

answer
28

Views

assign multiple values to variables in a subclass of the same class

Open to suggestions for a better title... If I remember this correctly, in Visual Basic you could assign multiple variables in a tree of some object with a 'with' constructor like this With Foo_Object.Foo_method .Bar_var1='foo' .Bar_var2='bar' End With Is there a similar construct in Python ?
oneindelijk
1

votes
1

answer
19

Views

Control Active Constructors Based on Index

I want to be able to control constructors with their id (location in array) I am not sure if it is possible to kill a single constructor's process but that is what i am looking for. I need to be able to stop and start constructors with their index in the list. class Worker { constructor(id, fname, l...
Nick
1

votes
0

answer
84

Views

Define function independent of specific value constructor (templates?)

Is it possible to write a function for generic types (in this case applicatives) without making assumptions about the name of type constructors? I can write the following: f :: Maybe a -> Maybe a f (Just a) = (Just a) That one works on Maybes and only instances with the Just constructor. But say I h...
lo tolmencre
1

votes
0

answer
43

Views

Class constructor does not take input parameters C++ (all attributes get the same value and the same value applies to all objects)

I created a class named Triangle that takes triangles as objects. The attributes are the ID of the triangle (m_ID), the index of the three vertices (m_S1, m_S2, m_S3) and the index of the three adjacent triangles (m_T1, m_T2, m_T3). I want to create a triangle object by passing input parameters in...
Michael Landry
0

votes
1

answer
26

Views

How to extend a class in JavaScript, when it has no default constructor?

In JavaScript, how do I extend a base class, when there is no constructor suitable to use when assigning the prototype of the new class? Solution... Must pass instanceof test. Must not modify existing constructor. Must call super constructor. Must not include an intermediate class I write. Must not...
ferisj
1

votes
2

answer
837

Views

C++ sharing object between two class

Suppose I have two class: FirstContainer and SecondContainer They hold the same reference (pass in their constructor) to the class ThirdContainer. FirstContainer and SecondContainer have the following methods: - addMemberToThirdContainer - delMemberOfThirdContainer - getThirdContainerMembers W...
soall
1

votes
1

answer
51

Views

No matching function to call with constructor(T* data)

My class node is a basic implementation of a simple Tree where each node has two child nodes. I've read 10 answers regarding the error message, but I could not figure out, where this goes wrong. error: no matching function for call to 'Lib::Node::Node(Math::Expression*&)' Lib::Node< Math::Expression...
infinitezero
1

votes
2

answer
670

Views

Spring Boot - Could not find a suitable constructor error

Hi I am trying to read a file as an argument from the main class and accessing the argument in another class in Spring boot. The main class looks like this public class DemorestApplication extends SpringBootServletInitializer { public static void main(String[] args) throws IOException { new Demorest...
Sudhanva c
1

votes
1

answer
51

Views

python - passing a list to constructor, incorrect number of arguments error

I'm passing a list to constructor, but python sees these as separate arguments: def __init__(self, a_parent, a_items): super.__init__(self, a_parent) self._parent = a_parent self._layout = QHBoxLayout() self._combo = QComboBox() for item in a_items: self._combo.addItem(item) self._layout.addWidget(s...
tim_tim

View additional questions